home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.004 / xemacs-1 / xemacs-19.13 / src / event-stream.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-09-01  |  117.7 KB  |  3,771 lines

  1. /* The portable interface to event streams.
  2.    Copyright (C) 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
  3.    Copyright (C) 1994, 1995 Amdahl Corporation.
  4.    Copyright (C) 1995 Board of Trustees, University of Illinois
  5.  
  6. This file is part of XEmacs.
  7.  
  8. XEmacs is free software; you can redistribute it and/or modify it
  9. under the terms of the GNU General Public License as published by the
  10. Free Software Foundation; either version 2, or (at your option) any
  11. later version.
  12.  
  13. XEmacs is distributed in the hope that it will be useful, but WITHOUT
  14. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15. FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  16. for more details.
  17.  
  18. You should have received a copy of the GNU General Public License
  19. along with XEmacs; see the file COPYING.  If not, write to the Free
  20. Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. /* Synched up with: Not in FSF. */
  23.  
  24. /* This file has been Mule-ized. */
  25.  
  26. /*
  27.  *    DANGER!!
  28.  *
  29.  *    If you ever change ANYTHING in this file, you MUST run the
  30.  *    testcases at the end to make sure that you haven't changed
  31.  *    the semantics of recent-keys, last-input-char, or keyboard
  32.  *    macros.  You'd be surprised how easy it is to break this.
  33.  *
  34.  */
  35.  
  36. #include <config.h>
  37. #include "lisp.h"
  38.  
  39. #include "buffer.h"
  40. #include "commands.h"
  41. #include "device.h"
  42. #include "device-tty.h"
  43. #include "events.h"
  44. #include "frame.h"
  45. #include "insdel.h"        /* for buffer_reset_changes */
  46. #include "keymap.h"
  47. #include "macros.h"        /* for defining_keyboard_macro */
  48. #include "opaque.h"
  49. #include "process.h"
  50. #include "sysdep.h"
  51. #include "window.h"
  52.  
  53. #include "sysproc.h"        /* select stuff */
  54. #include "systime.h"        /* to set Vlast_input_time */
  55.  
  56. #include <errno.h>
  57.  
  58. /* The number of keystrokes between auto-saves. */
  59. static int auto_save_interval;
  60.  
  61. Lisp_Object Qundefined; /* The symbol undefined; good a place as any... */
  62. Lisp_Object Qundefined_keystroke_sequence;
  63.  
  64. Lisp_Object Qcommand_execute;
  65.  
  66. Lisp_Object Qemacs_handle_focus_change;
  67.  
  68. Lisp_Object Vpre_command_hook, Vpost_command_hook;
  69. Lisp_Object Qpre_command_hook, Qpost_command_hook;
  70.  
  71. Lisp_Object Vlocal_pre_command_hook, Vlocal_post_command_hook;
  72. Lisp_Object Qlocal_pre_command_hook, Qlocal_post_command_hook;
  73.  
  74. /* Non-nil disable property on a command means
  75.    do not execute it; call disabled-command-hook's value instead. */
  76. Lisp_Object Qdisabled, Vdisabled_command_hook;
  77.  
  78. static void pre_command_hook (void);
  79. static void post_command_hook (void);
  80.  
  81. /* Last keyboard or mouse input event read as a command. */
  82. Lisp_Object Vlast_command_event;
  83.  
  84. /* The nearest ASCII equivalent of the above. */
  85. Lisp_Object Vlast_command_char;
  86.  
  87. /* Last keyboard or mouse event read for any purpose. */
  88. Lisp_Object Vlast_input_event;
  89.  
  90. /* The nearest ASCII equivalent of the above. */
  91. Lisp_Object Vlast_input_char;
  92.  
  93. /* If not Qnil, event objects to be read as the next command input */
  94. Lisp_Object Vunread_command_events;
  95. Lisp_Object Vunread_command_event; /* obsoleteness support */
  96.  
  97. static Lisp_Object Qunread_command_events, Qunread_command_event;
  98.  
  99. /* Previous command, represented by a Lisp object.
  100.    Does not include prefix commands and arg setting commands */
  101. Lisp_Object Vlast_command;
  102.  
  103. /* If a command sets this, the value goes into
  104.    previous-command for the next command. */
  105. Lisp_Object Vthis_command;
  106.  
  107. /* The value of point when the last command was executed.  */
  108. Bufpos last_point_position;
  109.  
  110. /* The frame that was current when the last command was started. */
  111. Lisp_Object Vlast_selected_frame;
  112.  
  113. /* The buffer that was current when the last command was started.  */
  114. Lisp_Object last_point_position_buffer;
  115.  
  116. /* A (16bit . 16bit) representation of the time of the last-command-event.
  117.  */
  118. Lisp_Object Vlast_input_time;
  119.  
  120. /* Character to recognize as the help char.  */
  121. Lisp_Object Vhelp_char;
  122.  
  123. /* Form to execute when help char is typed.  */
  124. Lisp_Object Vhelp_form;
  125.  
  126. /* Flag to tell QUIT that some interesting occurrence (e.g. a keypress)
  127.    may have happened. */
  128. volatile int something_happened;
  129.  
  130. /* Command to run when the help character follows a prefix key.  */
  131. Lisp_Object Vprefix_help_command;
  132.  
  133. /* User-supplied string to translate input characters through */
  134. Lisp_Object Vkeyboard_translate_table;
  135.  
  136. /* If control-meta-super-shift-X is undefined, try control-meta-super-x */
  137. Lisp_Object Vretry_undefined_key_binding_unshifted;
  138.  
  139. /* Mask of bits indicating the descriptors that we wait for input on.
  140.    These work as follows: */
  141. SELECT_TYPE input_wait_mask, non_fake_input_wait_mask;
  142. SELECT_TYPE process_only_mask, device_only_mask;
  143.  
  144. /* Device that corresponds to our controlling terminal */
  145. Lisp_Object Vcontrolling_terminal;
  146.  
  147.  
  148. /* The callback routines for the window system or terminal driver */
  149. struct event_stream *event_stream;
  150.  
  151. /* This structure is what we use to excapsulate the state of a command sequence
  152.    being composed; key events are executed by adding themselves to the command
  153.    builder; if the command builder is then complete (does not still represent
  154.    a prefix key sequence) it executes the corresponding command.
  155.  */
  156. struct command_builder
  157. {
  158.   /* Qnil, or a Lisp_Event representing the first event event read
  159.    *  after the last command completed.  Threaded. */
  160.   /* #### NYI */
  161.   Lisp_Object prefix_events;
  162.   /* Qnil, or a Lisp_Event representing event in the current 
  163.    *  keymap-lookup sequence.  Subsequent events are threaded via
  164.    *  the event's next slot */
  165.   Lisp_Object current_events;
  166.   /* Last elt of above  */
  167.   Lisp_Object most_current_event;
  168.   /* Last elt before function map code took over. */
  169.   Lisp_Object last_non_function_event;
  170.  
  171.   Bufbyte *echo_buf;
  172.   Bytecount echo_buf_length;          /* size of echo_buf */
  173.   Bytecount echo_buf_index;           /* index into echo_buf
  174.                        * -1 before doing echoing for new cmd */
  175.   int echo_esc_index;           /* for disgusting ESC => meta kludge */
  176.   /* Self-insert-command is magic in that it doesn't always push an undo-
  177.      boundary: up to 20 consecutive self-inserts can happen before an undo-
  178.      boundary is pushed.  This variable is that counter.
  179.      */
  180.   int self_insert_countdown;
  181. };
  182.  
  183. static struct command_builder *the_command_builder;
  184.  
  185. static void echo_key_event (struct command_builder *, Lisp_Object event);
  186. static void maybe_kbd_translate (Lisp_Object event);
  187.  
  188. /* This structure is basically a typeahead queue: things like
  189.    wait-reading-process-output will delay the execution of
  190.    keyboard and mouse events by pushing them here.
  191.  
  192.    Chained through event_next()
  193.    command_event_queue_tail is a pointer to the last-added element.
  194.  */
  195. static Lisp_Object command_event_queue;
  196. static struct Lisp_Event *command_event_queue_tail;
  197.  
  198. /* Nonzero means echo unfinished commands after this many seconds of pause. */
  199. static int echo_keystrokes;
  200.  
  201. /* The number of keystrokes since the last auto-save. */
  202. static int keystrokes_since_auto_save;
  203.  
  204. /* This is used to terminate the select(), when an event came in
  205.    through a signal (e.g. window-change or C-g on controlling TTY). */
  206. int signal_event_pipe[2];
  207.  
  208. /* Used by the C-g signal handler so that it will never "hard quit"
  209.    when waiting for an event.  Otherwise holding down C-g could
  210.    cause a suspension back to the shell, which is generally
  211.    undesirable. (#### This doesn't fully work.) */
  212.  
  213. int emacs_is_blocking;
  214.  
  215.  
  216. /**********************************************************************/
  217. /*             Low-level interfaces onto event methods                */
  218. /**********************************************************************/
  219.  
  220. enum event_stream_operation
  221. {
  222.   EVENT_STREAM_PROCESS,
  223.   EVENT_STREAM_TIMEOUT,
  224.   EVENT_STREAM_ADD_DEVICE,
  225.   EVENT_STREAM_READ
  226. };
  227.  
  228. static void
  229. check_event_stream_ok (enum event_stream_operation op)
  230. {
  231.   if (!event_stream && noninteractive)
  232.     {
  233.       switch (op)
  234.     {
  235.     case EVENT_STREAM_PROCESS:
  236.       error ("Can't start subprocesses in -batch mode");
  237.     case EVENT_STREAM_TIMEOUT:
  238.       error ("Can't add timeouts in -batch mode");
  239.     case EVENT_STREAM_ADD_DEVICE:
  240.       error ("Can't add devices in -batch mode");
  241.     case EVENT_STREAM_READ:
  242.       error ("Can't read events in -batch mode");
  243.     default:
  244.       abort ();
  245.     }
  246.     }
  247.   else if (!event_stream)
  248.     {
  249.       error ("event-stream callbacks not initialized (internal error?)");
  250.     }
  251. }
  252.  
  253. int
  254. event_stream_event_pending_p (int user)
  255. {
  256.   if (!event_stream)
  257.     return 0;
  258.   return event_stream->event_pending_p (user);
  259. }
  260.  
  261. void
  262. event_stream_next_event (struct Lisp_Event *event)
  263. {
  264.   Lisp_Object event_obj = Qnil;
  265.  
  266.   check_event_stream_ok (EVENT_STREAM_READ);
  267.  
  268.   /* If C-g was pressed, treat it as a character to be read.
  269.      Note that if C-g was pressed while we were blocking,
  270.      the SIGINT signal handler will be called.  It will
  271.      set Vquit_flag and write a byte on our "fake pipe",
  272.      which will unblock us. */
  273.   if (maybe_read_quit_event (event))
  274.     return;
  275.   
  276.   emacs_is_blocking = 1;
  277.   event_stream->next_event_cb (event);
  278.   emacs_is_blocking = 0;
  279.  
  280.   XSETEVENT (event_obj, event);
  281.   maybe_kbd_translate (event_obj);
  282. }
  283.  
  284. void
  285. event_stream_handle_magic_event (struct Lisp_Event *event)
  286. {
  287.   check_event_stream_ok (EVENT_STREAM_READ);
  288.   event_stream->handle_magic_event_cb (event);
  289. }
  290.  
  291. static int
  292. event_stream_add_timeout (EMACS_TIME timeout)
  293. {
  294.   check_event_stream_ok (EVENT_STREAM_TIMEOUT);
  295.   return event_stream->add_timeout_cb (timeout);
  296. }
  297.  
  298. static void
  299. event_stream_remove_timeout (int id)
  300. {
  301.   check_event_stream_ok (EVENT_STREAM_TIMEOUT);
  302.   event_stream->remove_timeout_cb (id);
  303. }
  304.  
  305. void
  306. event_stream_select_device (struct device *d)
  307. {
  308.   int infd = DEVICE_INFD (d);
  309.  
  310.   if (d->input_enabled)
  311.     {
  312.       Lisp_Object device;
  313.       XSETDEVICE (device, d);
  314.       signal_simple_error ("device already enabled for input", device);
  315.     }
  316.   check_event_stream_ok (EVENT_STREAM_ADD_DEVICE);
  317.   FD_SET (infd, &input_wait_mask);
  318.   FD_SET (infd, &non_fake_input_wait_mask);
  319.   FD_SET (infd, &device_only_mask);
  320.   event_stream->select_device_cb (d);
  321.   d->input_enabled = 1;
  322. }
  323.  
  324. void
  325. event_stream_unselect_device (struct device *d)
  326. {
  327.   int infd = DEVICE_INFD (d);
  328.  
  329.   if (!d->input_enabled)
  330.     {
  331.       Lisp_Object device;
  332.       XSETDEVICE (device, d);
  333.       signal_simple_error ("device already disabled for input", device);
  334.     }
  335.   check_event_stream_ok (EVENT_STREAM_ADD_DEVICE);
  336.   FD_CLR (infd, &input_wait_mask);
  337.   FD_CLR (infd, &non_fake_input_wait_mask);
  338.   FD_CLR (infd, &device_only_mask);
  339.   event_stream->unselect_device_cb (d);
  340.   d->input_enabled = 0;
  341. }
  342.  
  343. void
  344. event_stream_select_process (struct Lisp_Process *proc)
  345. {
  346.   int infd, outfd;
  347.  
  348.   check_event_stream_ok (EVENT_STREAM_PROCESS);
  349.   get_process_file_descriptors (proc, &infd, &outfd);
  350.   FD_SET (infd, &input_wait_mask);
  351.   FD_SET (infd, &non_fake_input_wait_mask);
  352.   FD_SET (infd, &process_only_mask);
  353.   event_stream->select_process_cb (proc);
  354. }
  355.  
  356. void
  357. event_stream_unselect_process (struct Lisp_Process *proc)
  358. {
  359.   int infd, outfd;
  360.  
  361.   check_event_stream_ok (EVENT_STREAM_PROCESS);
  362.   get_process_file_descriptors (proc, &infd, &outfd);
  363.   FD_CLR (infd, &input_wait_mask);
  364.   FD_CLR (infd, &non_fake_input_wait_mask);
  365.   FD_CLR (infd, &process_only_mask);
  366.   event_stream->unselect_process_cb (proc);
  367. }
  368.  
  369. void
  370. event_stream_quit_p (void)
  371. {
  372.   if (event_stream)
  373.     event_stream->quit_p_cb ();
  374. }
  375.  
  376.  
  377.  
  378. /**********************************************************************/
  379. /*                      Character prompting                           */
  380. /**********************************************************************/
  381.  
  382. static void
  383. echo_key_event (struct command_builder *command_builder,
  384.         Lisp_Object event)
  385. {
  386.   /* This function can GC */
  387.   char buf[255];
  388.   Bytecount buf_index = command_builder->echo_buf_index;
  389.   Bufbyte *e;
  390.   Bytecount len;
  391.  
  392.   if (buf_index < 0)
  393.   {
  394.     buf_index = 0;              /* We're echoing now */
  395.     clear_echo_area (selected_frame (), Qnil, 0);
  396.   }
  397.  
  398.   if (command_builder->echo_esc_index < 0
  399.       && event_matches_key_specifier_p (XEVENT (event), Vmeta_prefix_char))
  400.     /* Icky-poo */
  401.     command_builder->echo_esc_index = buf_index;
  402.  
  403.   format_event_object (buf, XEVENT (event), 1);
  404.   len = strlen (buf);
  405.   
  406.   if (len + buf_index + 4 > command_builder->echo_buf_length)
  407.     return;
  408.   e = command_builder->echo_buf + buf_index;
  409.   memcpy (e, buf, len);
  410.   e += len;
  411.  
  412.   e[0] = ' ';
  413.   e[1] = '-';
  414.   e[2] = ' ';
  415.   e[3] = 0;
  416.  
  417.   command_builder->echo_buf_index = buf_index + len + 1;
  418. }
  419.  
  420. static void
  421. maybe_echo_keys (struct command_builder *command_builder, int no_snooze)
  422. {
  423.   /* This function can GC */
  424.   struct frame *f = selected_frame ();
  425.   /* Message turns off echoing unless more keystrokes turn it on again. */
  426.   if (echo_area_active (f) && !EQ (Qcommand, echo_area_status (f)))
  427.     return;
  428.  
  429.   if (minibuf_level == 0 
  430.       && echo_keystrokes > 0 
  431.       && (no_snooze ||
  432.       !NILP (Fsit_for (make_number (echo_keystrokes), Qnil))))
  433.   {
  434.     echo_area_message (f, command_builder->echo_buf, Qnil, 0,
  435.                /* not echo_buf_index.  That doesn't include
  436.               the terminating " - ". */
  437.                strlen ((char *) command_builder->echo_buf),
  438.                Qcommand);
  439.   }
  440. }
  441.  
  442. static void
  443. reset_key_echo (struct command_builder *command_builder,
  444.                 int remove_echo_area_echo)
  445. {
  446.   /* This function can GC */
  447.   struct frame *f = selected_frame ();
  448.  
  449.   command_builder->echo_buf_index = -1;
  450.  
  451.   if (remove_echo_area_echo)
  452.     clear_echo_area (f, Qcommand, 0);
  453. }
  454.  
  455.  
  456. /**********************************************************************/
  457. /*                          random junk                               */
  458. /**********************************************************************/
  459.  
  460. static void
  461. maybe_kbd_translate (Lisp_Object event)
  462. {
  463.   struct Lisp_Event ev2;
  464.   Emchar c;
  465.  
  466.   if (!STRINGP (Vkeyboard_translate_table))
  467.     return;
  468.   c = event_to_character (XEVENT (event), 0, 0, 0);
  469.   if (c == -1)
  470.     return;
  471.   if (string_char_length (XSTRING (Vkeyboard_translate_table)) <= c)
  472.     return;
  473.   c = string_char (XSTRING (Vkeyboard_translate_table), c);
  474.  
  475.   /* This used to call Fcharacter_to_event() directly into EVENT,
  476.      but that can eradicate timestamps and other such stuff.
  477.      This way is safer. */
  478.   ev2.event_type = empty_event;
  479.   character_to_event (c, &ev2, XDEVICE (XEVENT (event)->device));
  480.   XEVENT (event)->event.key.keysym = ev2.event.key.keysym;
  481.   XEVENT (event)->event.key.modifiers = ev2.event.key.modifiers;
  482. }
  483.  
  484. /* NB: The following auto-save stuff is in keyboard.c in FSFmacs, and
  485.    keystrokes_since_auto_save is equivalent to the difference between
  486.    num_nonmacro_input_chars and last_auto_save. */
  487.  
  488. /* When an auto-save happens, record the "time", and don't do again soon.  */
  489.  
  490. void
  491. record_auto_save (void)
  492. {
  493.   keystrokes_since_auto_save = 0;
  494. }
  495.   
  496. /* Make an auto save happen as soon as possible at command level.  */
  497.  
  498. void
  499. force_auto_save_soon (void)
  500. {
  501.   keystrokes_since_auto_save = 1 + max (auto_save_interval, 20);
  502.  
  503. #if 0 /* FSFmacs */
  504.   record_asynch_buffer_change ();
  505. #endif
  506. }
  507.  
  508. static void
  509. maybe_do_auto_save (void)
  510. {
  511.   /* This function can GC */
  512.   keystrokes_since_auto_save++;
  513.   if (auto_save_interval > 0 &&
  514.       keystrokes_since_auto_save > max (auto_save_interval, 20) &&
  515.       !detect_input_pending ())
  516.     {
  517.       Fdo_auto_save (Qnil, Qnil);
  518.       record_auto_save ();
  519.     }
  520. }
  521.  
  522. static Lisp_Object
  523. print_help (Lisp_Object object)
  524. {
  525.   Fprinc (object, Qnil);
  526.   return Qnil;
  527. }
  528.  
  529. static void
  530. execute_help_form (struct command_builder *command_builder,
  531.                    Lisp_Object event)
  532. {
  533.   /* This function can GC */
  534.   Lisp_Object help = Qnil;
  535.   int speccount = specpdl_depth ();
  536.   Bytecount esc_index = command_builder->echo_esc_index;
  537.   Bytecount buf_index = command_builder->echo_buf_index;
  538.   Lisp_Object echo = ((buf_index <= 0)
  539.                       ? Qnil
  540.                       : make_string (command_builder->echo_buf,
  541.                      buf_index));
  542.   struct gcpro gcpro1, gcpro2;
  543.   GCPRO2 (echo, help);
  544.  
  545.   record_unwind_protect (Fset_window_configuration,
  546.              Fcurrent_window_configuration (Qnil));
  547.   reset_key_echo (command_builder, 1);
  548.  
  549.   help = Feval (Vhelp_form);
  550.   if (STRINGP (help))
  551.     internal_with_output_to_temp_buffer ("*Help*",
  552.                      print_help, help, Qnil);
  553.   Fnext_command_event (event, Qnil);
  554.   /* Remove the help from the frame */
  555.   unbind_to (speccount, Qnil);
  556.   /* Hmmmm.  Tricky.  The unbind restores an old window configuration,
  557.      apparently bypassing any setting of windows_structure_changed.
  558.      So we need to set it so that things get redrawn properly. */
  559.   /* #### This is massive overkill.  Look at doing it better once the
  560.      new redisplay is fully in place. */
  561.   {
  562.     Lisp_Object dev;
  563.     DEVICE_LOOP (dev)
  564.       {
  565.     Lisp_Object frame;
  566.  
  567.     for (frame = DEVICE_FRAME_LIST (XDEVICE (XCAR (dev)));
  568.          !NILP (frame);
  569.          frame = XCDR (frame))
  570.       {
  571.         MARK_FRAME_WINDOWS_STRUCTURE_CHANGED (XFRAME (XCAR (frame)));
  572.       }
  573.       }
  574.   }
  575.  
  576.   redisplay ();
  577.   if (event_matches_key_specifier_p (XEVENT (event), make_number (' ')))
  578.     {
  579.       /* Discard next key if is is a space */
  580.       reset_key_echo (command_builder, 1);
  581.       Fnext_command_event (event, Qnil);
  582.     }
  583.  
  584.   command_builder->echo_esc_index = esc_index;
  585.   command_builder->echo_buf_index = buf_index;
  586.   if (buf_index > 0)
  587.     memcpy (command_builder->echo_buf,
  588.             string_data (XSTRING (echo)), buf_index + 1); /* terminating 0 */
  589.   UNGCPRO;
  590. }
  591.  
  592.  
  593. /**********************************************************************/
  594. /*                          input pending                             */
  595. /**********************************************************************/
  596.  
  597. int
  598. detect_input_pending (void)
  599. {
  600.   /* Always call the event_pending_p hook even if there's an unread
  601.      character, because that might do some needed ^G detection (on
  602.      systems without SIGIO, for example).
  603.    */
  604.   if (event_stream_event_pending_p (1))
  605.     return 1;
  606.   if (!NILP (Vunread_command_events) || !NILP (Vunread_command_event))
  607.     return 1;
  608.   if (!NILP (command_event_queue))
  609.     {
  610.       struct Lisp_Event *e;
  611.       for (e = XEVENT (command_event_queue);
  612.            e;
  613.            e = event_next (e))
  614.       {
  615.         if (e->event_type != eval_event)
  616.           return (1);
  617.       }
  618.     }
  619.   return 0;
  620. }
  621.  
  622. DEFUN ("input-pending-p", Finput_pending_p, Sinput_pending_p, 0, 0, 0,
  623.   "T if command input is currently available with no waiting.\n\
  624. Actually, the value is nil only if we can be sure that no input is available.")
  625.   ()
  626. {
  627.   return ((detect_input_pending ()) ? Qt : Qnil);
  628. }
  629.  
  630.  
  631. /**********************************************************************/
  632. /*                            timeouts                                */
  633. /**********************************************************************/
  634.  
  635. /**** Low-level timeout functions. ****
  636.  
  637.    These functions maintain a sorted list of one-shot timeouts (where
  638.    the timeouts are in absolute time).  They are intended for use by
  639.    functions that need to convert a list of absolute timeouts into a
  640.    series of intervals to wait for. */
  641.  
  642. static int low_level_timeout_id_tick;
  643.  
  644. struct low_level_timeout_blocktype
  645. {
  646.   Blocktype_declare (struct low_level_timeout);
  647. } *the_low_level_timeout_blocktype;
  648.  
  649. /* Add a one-shot timeout at time TIME to TIMEOUT_LIST.  Return
  650.    a unique ID identifying the timeout. */
  651.  
  652. int
  653. add_low_level_timeout (struct low_level_timeout **timeout_list,
  654.                EMACS_TIME time)
  655. {
  656.   struct low_level_timeout *tm;
  657.   struct low_level_timeout *t, **tt;
  658.  
  659.   /* Allocate a new time struct. */
  660.  
  661.   tm = Blocktype_alloc (the_low_level_timeout_blocktype);
  662.   tm->next = NULL;
  663.   tm->id = low_level_timeout_id_tick++;
  664.   tm->time = time;
  665.  
  666.   /* Add it to the queue. */
  667.  
  668.   tt = timeout_list;
  669.   t  = *tt;
  670.   while (t && EMACS_TIME_EQUAL_OR_GREATER (tm->time, t->time))
  671.     {
  672.       tt = &t->next;
  673.       t  = *tt;
  674.     }
  675.   tm->next = t;
  676.   *tt = tm;
  677.  
  678.   return tm->id;
  679. }
  680.  
  681. /* Remove the low-level timeout identified by ID from TIMEOUT_LIST.
  682.    If the timeout is not there, do nothing. */
  683.  
  684. void
  685. remove_low_level_timeout (struct low_level_timeout **timeout_list, int id)
  686. {
  687.   struct low_level_timeout *t, *prev;
  688.   
  689.   /* find it */
  690.   
  691.   for (t = *timeout_list, prev = NULL; t && t->id != id; t = t->next)
  692.     prev = t;
  693.   
  694.   if (!t)
  695.     return; /* couldn't find it */
  696.  
  697.   if (!prev)
  698.     *timeout_list = t->next;
  699.   else prev->next = t->next;
  700.  
  701.   Blocktype_free (the_low_level_timeout_blocktype, t);
  702. }
  703.  
  704. /* If there are timeouts on TIMEOUT_LIST, store the relative time
  705.    interval to the first timeout on the list into INTERVAL and
  706.    return 1.  Otherwise, return 0. */
  707.  
  708. int
  709. get_low_level_timeout_interval (struct low_level_timeout *timeout_list,
  710.                 EMACS_TIME *interval)
  711. {
  712.   if (!timeout_list) /* no timer events; block indefinitely */
  713.     return 0;
  714.   else
  715.     {
  716.       EMACS_TIME current_time;
  717.       
  718.       /* The time to block is the difference between the first
  719.      (earliest) timer on the queue and the current time.
  720.      If that is negative, then the timer will fire immediately
  721.      but we still have to call select(), with a zero-valued
  722.      timeout: user events must have precedence over timer events. */
  723.       EMACS_GET_TIME (current_time);
  724.       if (EMACS_TIME_GREATER (timeout_list->time, current_time))
  725.     EMACS_SUB_TIME (*interval, timeout_list->time,
  726.             current_time);
  727.       else
  728.     EMACS_SET_SECS_USECS (*interval, 0, 0);
  729.       return 1;
  730.     }
  731. }
  732.  
  733. /* Pop the first (i.e. soonest) timeout off of TIMEOUT_LIST and return
  734.    its ID.  Also, if TIME_OUT is not 0, store the absolute time of the
  735.    timeout into TIME_OUT. */
  736.  
  737. int
  738. pop_low_level_timeout (struct low_level_timeout **timeout_list,
  739.                EMACS_TIME *time_out)
  740. {
  741.   struct low_level_timeout *tm = *timeout_list;
  742.   int id;
  743.  
  744.   assert (tm);
  745.   id = tm->id;
  746.   if (time_out)
  747.     *time_out = tm->time;
  748.   *timeout_list = tm->next;
  749.   Blocktype_free (the_low_level_timeout_blocktype, tm);
  750.   return id;
  751. }
  752.  
  753.  
  754. /**** High-level timeout functions. ****/
  755.  
  756. static int timeout_id_tick;
  757.  
  758. /* Since timeout structures contain Lisp_Objects, they need to be GC'd
  759.    properly.  The opaque data type provides a convenient way of doing
  760.    this without having to create a new Lisp object, since we can
  761.    provide our own mark function. */
  762.  
  763. struct timeout
  764. {
  765.   int id; /* Id we use to identify the timeout over its lifetime */
  766.   int interval_id; /* Id for this particular interval; this may
  767.               be different each time the timeout is
  768.               signalled.*/
  769.   Lisp_Object function, object; /* Function and object associated
  770.                    with timeout. */
  771.   EMACS_TIME next_signal_time;  /* Absolute time when the timeout
  772.                    is next going to be signalled. */
  773.   unsigned int resignal_msecs;  /* How far after the next timeout
  774.                    should the one after that
  775.                    occur? */
  776. };
  777.  
  778. static Lisp_Object pending_timeout_list, pending_async_timeout_list;
  779.  
  780. static Lisp_Object
  781. mark_timeout (Lisp_Object obj, void (*markobj) (Lisp_Object))
  782. {
  783.   struct timeout *tm = (struct timeout *) XOPAQUE_DATA (obj);
  784.   (markobj) (tm->function);
  785.   return tm->object;
  786. }
  787.  
  788. int
  789. event_stream_generate_wakeup (unsigned int milliseconds,
  790.                   unsigned int vanilliseconds,
  791.                   Lisp_Object function, Lisp_Object object,
  792.                   int async_p)
  793. {
  794.   Lisp_Object op = make_opaque (sizeof (struct timeout), 0);
  795.   struct timeout *timeout = (struct timeout *) XOPAQUE_DATA (op);
  796.   EMACS_TIME current_time;
  797.   EMACS_TIME interval;
  798.  
  799.   set_opaque_markfun (op, mark_timeout);
  800.   timeout->id = timeout_id_tick++;
  801.   timeout->resignal_msecs = vanilliseconds;
  802.   timeout->function = function;
  803.   timeout->object = object;
  804.  
  805.   EMACS_GET_TIME (current_time);
  806.   EMACS_SET_SECS_USECS (interval, milliseconds / 1000,
  807.             1000 * (milliseconds % 1000));
  808.   EMACS_ADD_TIME (timeout->next_signal_time, current_time, interval);
  809.  
  810.   if (async_p)
  811.     {
  812.       timeout->interval_id =
  813.     event_stream_add_async_timeout (timeout->next_signal_time);
  814.       pending_async_timeout_list = Fcons (op, pending_async_timeout_list);
  815.     }
  816.   else
  817.     {
  818.       timeout->interval_id =
  819.     event_stream_add_timeout (timeout->next_signal_time);
  820.       pending_timeout_list = Fcons (op, pending_timeout_list);
  821.     }
  822.   return timeout->id;
  823. }
  824.  
  825. static struct timeout *
  826. event_stream_resignal_wakeup (int interval_id, int async_p)
  827. {
  828.   Lisp_Object op = Qnil, rest;
  829.   struct timeout *timeout;
  830.   Lisp_Object *timeout_list;
  831.   struct gcpro gcpro1;
  832.  
  833.   GCPRO1 (op); /* just in case ...  because it's removed from the list
  834.           for awhile. */
  835.  
  836.   if (async_p)
  837.     timeout_list = &pending_async_timeout_list;
  838.   else
  839.     timeout_list = &pending_timeout_list;
  840.  
  841.   /* Find the timeout on the list of pending ones. */
  842.   LIST_LOOP (rest, *timeout_list)
  843.     {
  844.       timeout = (struct timeout *) XOPAQUE_DATA (XCAR (rest));
  845.       if (timeout->interval_id == interval_id)
  846.     break;
  847.     }
  848.  
  849.   assert (!NILP (rest));
  850.   op = XCAR (rest);
  851.   timeout = (struct timeout *) XOPAQUE_DATA (op);
  852.  
  853.   /* Remove this one from the list of pending timeouts */
  854.   *timeout_list = delq_no_quit (op, *timeout_list);
  855.  
  856.   /* If this timeout wants to be resignalled, do it now. */
  857.   if (timeout->resignal_msecs)
  858.     {
  859.       EMACS_TIME current_time;
  860.       EMACS_TIME interval;
  861.  
  862.       /* Determine the time that the next resignalling should occur.
  863.      We do that by adding the interval time to the last signalled
  864.      time until we get a time that's current.
  865.  
  866.      (This way, it doesn't matter if the timeout was signalled
  867.      exactly when we asked for it, or at some time later.)
  868.      */
  869.       EMACS_GET_TIME (current_time);
  870.       EMACS_SET_SECS_USECS (interval, timeout->resignal_msecs / 1000,
  871.                 1000 * (timeout->resignal_msecs % 1000));
  872.       do
  873.     {
  874.       EMACS_ADD_TIME (timeout->next_signal_time, timeout->next_signal_time,
  875.               interval);
  876.     } while (EMACS_TIME_GREATER (current_time, timeout->next_signal_time));
  877.  
  878.       if (async_p)
  879.         timeout->interval_id =
  880.       event_stream_add_async_timeout (timeout->next_signal_time);
  881.       else
  882.         timeout->interval_id =
  883.       event_stream_add_timeout (timeout->next_signal_time);
  884.       /* Add back onto the list.  Note that the effect of this
  885.          is to move frequently-hit timeouts to the front of the
  886.      list, which is a good thing. */
  887.       *timeout_list = Fcons (op, *timeout_list);
  888.     }
  889.   
  890.   UNGCPRO;
  891.   return timeout;
  892. }
  893.  
  894. static void
  895. event_stream_disable_wakeup (int id, int async_p)
  896. {
  897.   struct timeout *timeout = 0;
  898.   Lisp_Object rest = Qnil;
  899.   Lisp_Object *timeout_list;
  900.  
  901.   if (async_p)
  902.     timeout_list = &pending_async_timeout_list;
  903.   else
  904.     timeout_list = &pending_timeout_list;
  905.  
  906.   /* Find the timeout on the list of pending ones, if it's still there. */
  907.   LIST_LOOP (rest, *timeout_list)
  908.     {
  909.       timeout = (struct timeout *) XOPAQUE_DATA (XCAR (rest));
  910.       if (timeout->id == id)
  911.     break;
  912.     }
  913.  
  914.   /* If we found it, remove it from the list and disable the pending
  915.      one-shot. */
  916.   if (!NILP (rest))
  917.     {
  918.       *timeout_list =
  919.     delq_no_quit (XCAR (rest), *timeout_list);
  920.       if (async_p)
  921.     event_stream_remove_async_timeout (timeout->interval_id);
  922.       else
  923.     event_stream_remove_timeout (timeout->interval_id);
  924.     }
  925. }
  926.  
  927.  
  928. /**** Asynch. timeout functions (see also signal.c) ****/
  929.  
  930. #if !defined (SIGIO) && !defined (DONT_POLL_FOR_QUIT)
  931. extern int poll_for_quit_id;
  932. #endif
  933.  
  934. #ifndef SIGCHLD
  935. extern int poll_for_sigchld_id;
  936. #endif
  937.  
  938. void
  939. event_stream_deal_with_async_timeout (int interval_id)
  940. {
  941.   /* This function can GC */
  942.   struct timeout *timeout =
  943.     event_stream_resignal_wakeup (interval_id, 1);
  944.  
  945. #if !defined (SIGIO) && !defined (DONT_POLL_FOR_QUIT)
  946.   if (timeout->id == poll_for_quit_id)
  947.     {
  948.       quit_check_signal_happened = 1;
  949.       quit_check_signal_tick_count++;
  950.       return;
  951.     }
  952. #endif
  953.  
  954. #ifndef SIGCHLD
  955.   if (timeout->id == poll_for_sigchld_id)
  956.     {
  957.       kick_status_notify ();
  958.       return;
  959.     }
  960. #endif
  961.  
  962.   call1_trapping_errors ("Error in asynchronous timeout callback",
  963.              timeout->function, timeout->object);
  964. }
  965.  
  966.  
  967. /**** Lisp-level timeout functions. ****/
  968.  
  969. static unsigned long
  970. lisp_number_to_milliseconds (Lisp_Object secs, int allow_0)
  971. {
  972.   unsigned long msecs;
  973. #ifdef LISP_FLOAT_TYPE
  974.   double fsecs;
  975.   CHECK_INT_OR_FLOAT (secs, 0);
  976.   fsecs = XFLOATINT (secs);
  977. #else
  978.   long fsecs;
  979.   CHECK_INT_OR_FLOAT (secs, 0);
  980.   fsecs = XINT (secs);
  981. #endif
  982.   msecs = 1000 * fsecs;
  983.   if (fsecs < 0)
  984.     signal_simple_error ("timeout is negative", secs);
  985.   if (!allow_0 && fsecs == 0)
  986.     signal_simple_error ("timeout is non-positive", secs);
  987.   if (fsecs >= (((unsigned int) 0xFFFFFFFF) / 1000))
  988.     signal_simple_error
  989.       ("timeout would exceed 32 bits when represented in milliseconds", secs);
  990.   return msecs;
  991. }
  992.  
  993. DEFUN ("add-timeout", Fadd_timeout, Sadd_timeout, 3, 4, 0,
  994.  "Add a timeout, to be signaled after the timeout period has elapsed.\n\
  995. SECS is a number of seconds, expressed as an integer or a float.\n\
  996. FUNCTION will be called after that many seconds have elapsed, with one\n\
  997. argument, the given OBJECT.  If the optional RESIGNAL argument is provided,\n\
  998. then after this timeout expires, `add-timeout' will automatically be called\n\
  999. again with RESIGNAL as the first argument.\n\
  1000. \n\
  1001. This function returns an object which is the id number of this particular\n\
  1002. timeout.  You can pass that object to `disable-timeout' to turn off the\n\
  1003. timeout before it has been signalled.\n\
  1004. \n\
  1005. NOTE: Id numbers as returned by this function are in a distinct namespace\n\
  1006. from those returned by `add-async-timeout'.  This means that the same id\n\
  1007. number could refer to a pending synchronous timeout and a different pending\n\
  1008. asynchronous timeout, and that you cannot pass an id from `add-timeout'\n\
  1009. to `disable-async-timeout', or vice-versa.\n\
  1010. \n\
  1011. The number of seconds may be expressed as a floating-point number, in which\n\
  1012. case some fractional part of a second will be used.  Caveat: the usable\n\
  1013. timeout granularity will vary from system to system.\n\
  1014. \n\
  1015. Adding a timeout causes a timeout event to be returned by `next-event', and\n\
  1016. the function will be invoked by `dispatch-event,' so if emacs is in a tight\n\
  1017. loop, the function will not be invoked until the next call to sit-for or\n\
  1018. until the return to top-level (the same is true of process filters).\n\
  1019. \n\
  1020. If you need to have a timeout executed even when XEmacs is in the midst of\n\
  1021. running Lisp code, use `add-async-timeout'.\n\
  1022. \n\
  1023. WARNING: if you are thinking of calling add-timeout from inside of a\n\
  1024. callback function as a way of resignalling a timeout, think again.  There\n\
  1025. is a race condition.  That's why the RESIGNAL argument exists.")
  1026.      (secs, function, object, resignal)
  1027.      Lisp_Object secs, function, object, resignal;
  1028. {
  1029.   unsigned long msecs = lisp_number_to_milliseconds (secs, 0);
  1030.   unsigned long msecs2 = (NILP (resignal) ? 0 :
  1031.               lisp_number_to_milliseconds (resignal, 0));
  1032.   int id;
  1033.   Lisp_Object lid;
  1034.   id = event_stream_generate_wakeup (msecs, msecs2, function, object, 0);
  1035.   lid = make_number (id);
  1036.   if (id != XINT (lid)) abort ();
  1037.   return lid;
  1038. }
  1039.  
  1040. DEFUN ("disable-timeout", Fdisable_timeout, Sdisable_timeout, 1, 1, 0,
  1041.  "Disable a timeout from signalling any more.\n\
  1042. ID should be a timeout id number as returned by `add-timeout'.  If ID\n\
  1043. corresponds to a one-shot timeout that has already signalled, nothing\n\
  1044. will happen.\n\
  1045. \n\
  1046. It will not work to call this function on an id number returned by\n\
  1047. `add-async-timeout'.  Use `disable-async-timeout' for that.")
  1048.      (id)
  1049.      Lisp_Object id;
  1050. {
  1051.   CHECK_INT (id, 0);
  1052.   event_stream_disable_wakeup (XINT (id), 0);
  1053.   return Qnil;
  1054. }
  1055.  
  1056. DEFUN ("add-async-timeout", Fadd_async_timeout, Sadd_async_timeout, 3, 4, 0,
  1057.  "Add an asynchronous timeout, to be signaled after an interval has elapsed.\n\
  1058. SECS is a number of seconds, expressed as an integer or a float.\n\
  1059. FUNCTION will be called after that many seconds have elapsed, with one\n\
  1060. argument, the given OBJECT.  If the optional RESIGNAL argument is provided,\n\
  1061. then after this timeout expires, `add-async-timeout' will automatically be\n\
  1062. called again with RESIGNAL as the first argument.\n\
  1063. \n\
  1064. This function returns an object which is the id number of this particular\n\
  1065. timeout.  You can pass that object to `disable-async-timeout' to turn off\n\
  1066. the timeout before it has been signalled.\n\
  1067. \n\
  1068. NOTE: Id numbers as returned by this function are in a distinct namespace\n\
  1069. from those returned by `add-timeout'.  This means that the same id number\n\
  1070. could refer to a pending synchronous timeout and a different pending\n\
  1071. asynchronous timeout, and that you cannot pass an id from\n\
  1072. `add-async-timeout' to `disable-timeout', or vice-versa.\n\
  1073. \n\
  1074. The number of seconds may be expressed as a floating-point number, in which\n\
  1075. case some fractional part of a second will be used.  Caveat: the usable\n\
  1076. timeout granularity will vary from system to system.\n\
  1077. \n\
  1078. Adding an asynchronous timeout causes the function to be invoked as soon\n\
  1079. as the timeout occurs, even if XEmacs is in the midst of executing some\n\
  1080. other code. (This is unlike the synchronous timeouts added with\n\
  1081. `add-timeout', where the timeout will only be signalled when XEmacs is\n\
  1082. waiting for events, i.e. the next return to top-level or invocation of\n\
  1083. `sit-for' or related functions.) This means that the function that is\n\
  1084. called *must* not signal an error or change any global state (e.g. switch\n\
  1085. buffers or windows) except when locking code is in place to make sure\n\
  1086. that race conditions don't occur in the interaction between the\n\
  1087. asynchronous timeout function and other code.\n\
  1088. \n\
  1089. Under most circumstances, you should use `add-timeout' instead, as it is\n\
  1090. much safer.  Asynchronous timeouts should only be used when such behavior\n\
  1091. is really necessary.\n\
  1092. \n\
  1093. Asynchronous timeouts are blocked and will not occur when `inhibit-quit'\n\
  1094. is non-nil.  As soon as `inhibit-quit' becomes nil again, any pending\n\
  1095. asynchronous timeouts will get called immediately. (Multiple occurrences\n\
  1096. of the same asynchronous timeout are not queued, however.) While the\n\
  1097. callback function of an asynchronous timeout is invoked, `inhibit-quit'\n\
  1098. is automatically bound to non-nil, and thus other asynchronous timeouts\n\
  1099. will be blocked unless the callback function explicitly sets `inhibit-quit'\n\
  1100. to nil.\n\
  1101. \n\
  1102. WARNING: if you are thinking of calling `add-async-timeout' from inside of a\n\
  1103. callback function as a way of resignalling a timeout, think again.  There\n\
  1104. is a race condition.  That's why the RESIGNAL argument exists.")
  1105.      (secs, function, object, resignal)
  1106.      Lisp_Object secs, function, object, resignal;
  1107. {
  1108.   unsigned long msecs = lisp_number_to_milliseconds (secs, 0);
  1109.   unsigned long msecs2 = (NILP (resignal) ? 0 :
  1110.               lisp_number_to_milliseconds (resignal, 0));
  1111.   int id;
  1112.   Lisp_Object lid;
  1113.   id = event_stream_generate_wakeup (msecs, msecs2, function, object, 1);
  1114.   lid = make_number (id);
  1115.   if (id != XINT (lid)) abort ();
  1116.   return lid;
  1117. }
  1118.  
  1119. DEFUN ("disable-async-timeout", Fdisable_async_timeout,
  1120.        Sdisable_async_timeout, 1, 1, 0,
  1121.  "Disable an asynchronous timeout from signalling any more.\n\
  1122. ID should be a timeout id number as returned by `add-async-timeout'.  If ID\n\
  1123. corresponds to a one-shot timeout that has already signalled, nothing\n\
  1124. will happen.\n\
  1125. \n\
  1126. It will not work to call this function on an id number returned by\n\
  1127. `add-timeout'.  Use `disable-timeout' for that.")
  1128.      (id)
  1129.      Lisp_Object id;
  1130. {
  1131.   CHECK_INT (id, 0);
  1132.   event_stream_disable_wakeup (XINT (id), 1);
  1133.   return Qnil;
  1134. }
  1135.  
  1136.  
  1137. /**********************************************************************/
  1138. /*                    enqueuing and dequeuing events                  */
  1139. /**********************************************************************/
  1140.  
  1141. /* used both by enqueue_command_event() and enqueue_Xt_dispatch_event() */
  1142.  
  1143. void
  1144. enqueue_event (Lisp_Object event, Lisp_Object *head, struct Lisp_Event **tail)
  1145. {
  1146.   struct Lisp_Event *e = XEVENT (event);
  1147.   if (event_next (e))
  1148.     abort ();
  1149.   if (*tail && *tail == e)
  1150.     abort ();
  1151.  
  1152.   if (*tail)
  1153.     set_event_next (*tail, e);
  1154.   else
  1155.    *head = event;
  1156.   *tail = e;
  1157.   
  1158.   if (e == event_next (e))
  1159.     abort ();
  1160. }
  1161.  
  1162. Lisp_Object
  1163. dequeue_event (Lisp_Object *head, struct Lisp_Event **tail)
  1164. {
  1165.   Lisp_Object event = Qnil;
  1166.   struct Lisp_Event *e;
  1167.  
  1168.   e = XEVENT (*head);
  1169.   XSETEVENT (event, e);
  1170.   
  1171.   if (!event_next (e))
  1172.     {
  1173.       *tail = 0;
  1174.       *head = Qnil;
  1175.     }
  1176.   else
  1177.     {
  1178.       XSETEVENT (*head, event_next (e));
  1179.     }
  1180.   set_event_next (e, 0);
  1181.   return event;
  1182. }
  1183.  
  1184. /* Add an event to the back of the command-event queue: it will be the next
  1185.    event read after all pending events.   This only works on keyboard,
  1186.    mouse-click, misc-user, and eval events.
  1187.  */
  1188. void
  1189. enqueue_command_event (Lisp_Object event)
  1190. {
  1191.   enqueue_event (event, &command_event_queue, &command_event_queue_tail);
  1192. }
  1193.  
  1194. Lisp_Object
  1195. dequeue_command_event (void)
  1196. {
  1197.   return dequeue_event (&command_event_queue, &command_event_queue_tail);
  1198. }
  1199.  
  1200. /* put the event on the typeahead queue, unless
  1201.    the event is the quit char, in which case the `QUIT'
  1202.    which will occur on the next trip through this loop is
  1203.    all the processing we should do - leaving it on the queue
  1204.    would cause the quit to be processed twice.
  1205.    */
  1206. static void
  1207. enqueue_command_event_1 (Lisp_Object event_to_copy)
  1208. {
  1209.   /* do not call check_quit() here.  Vquit_flag was set in
  1210.      next_event_internal. */
  1211.   if (NILP (Vquit_flag))
  1212.     enqueue_command_event (Fcopy_event (event_to_copy, Qnil));
  1213. }
  1214.  
  1215. DEFUN ("enqueue-eval-event", Fenqueue_eval_event, Senqueue_eval_event,
  1216.        2, 2, 0, 
  1217.        "Add an eval event to the back of the eval event queue.\n\
  1218. When this event is dispatched, FUNCTION (which should be a function\n\
  1219. of one argument) will be called with OBJECT as its argument.\n\
  1220. See `next-event' for a description of event types and how events\n\
  1221. are received.")
  1222.   (function, object)
  1223.      Lisp_Object function, object;
  1224. {
  1225.   Lisp_Object event;
  1226.  
  1227.   event = Fallocate_event ();
  1228.  
  1229.   XEVENT (event)->event_type = eval_event;
  1230.   XEVENT (event)->event.eval.function = function;
  1231.   XEVENT (event)->event.eval.object = object;
  1232.   enqueue_command_event (event);
  1233.  
  1234.   return event;
  1235. }
  1236.  
  1237. Lisp_Object
  1238. enqueue_misc_user_event (Lisp_Object function, Lisp_Object object)
  1239. {
  1240.   Lisp_Object event;
  1241.  
  1242.   event = Fallocate_event ();
  1243.  
  1244.   XEVENT (event)->event_type = misc_user_event;
  1245.   XEVENT (event)->event.eval.function = function;
  1246.   XEVENT (event)->event.eval.object = object;
  1247.   enqueue_command_event (event);
  1248.  
  1249.   return event;
  1250. }
  1251.  
  1252.  
  1253. /**********************************************************************/
  1254. /*                       focus-event handling                         */
  1255. /**********************************************************************/
  1256.  
  1257. static void
  1258. run_select_frame_hook (void)
  1259. {
  1260.  if (!NILP (Vrun_hooks))
  1261.     call1 (Vrun_hooks, Qselect_frame_hook);
  1262. }
  1263.  
  1264. static void
  1265. run_deselect_frame_hook (void)
  1266. {
  1267.   if (!NILP (Vrun_hooks))
  1268.     call1 (Vrun_hooks, Qdeselect_frame_hook);
  1269. }
  1270.  
  1271. /* When select-frame is called, we want to tell the window system that
  1272.    the focus should be changed to point to the new frame.  However,
  1273.    sometimes Lisp functions will temporarily change the selected frame
  1274.    (e.g. to call a function that operates on the selected frame),
  1275.    and it's annoying if this focus-change happens exactly when
  1276.    select-frame is called, because then you get some flickering of the
  1277.    window-manager border and perhaps other undesirable results.  We
  1278.    really only want to change the focus when we're about to retrieve
  1279.    an event from the user.  To do this, we keep track of the frame
  1280.    where the window-manager focus lies on, and just before waiting
  1281.    for user events, check the currently selected frame and change
  1282.    the focus as necessary. */
  1283.  
  1284. static void
  1285. investigate_frame_change (void)
  1286. {
  1287.   Lisp_Object dev;
  1288.  
  1289.   /* if the selected frame was changed, change the window-system
  1290.      focus to the new frame.  We don't do it when select-frame was
  1291.      called, to avoid flickering and other unwanted side effects when
  1292.      the frame is just changed temporarily. */
  1293.   DEVICE_LOOP (dev)
  1294.     {
  1295.       struct device *d = XDEVICE (XCAR (dev));
  1296.       Lisp_Object sel_frame = DEVICE_SELECTED_FRAME (d);
  1297.  
  1298.       if (!NILP (sel_frame) &&
  1299.       !EQ (DEVICE_FRAME_THAT_OUGHT_TO_HAVE_FOCUS (d), sel_frame) &&
  1300.       !NILP (DEVICE_FRAME_WITH_FOCUS (d)) &&
  1301.       !EQ (DEVICE_FRAME_WITH_FOCUS (d), sel_frame))
  1302.     {
  1303.       /* prevent us from issuing the same request more than once */
  1304.       DEVICE_FRAME_THAT_OUGHT_TO_HAVE_FOCUS (d) = sel_frame;
  1305.       MAYBE_DEVMETH (d, focus_on_frame, (XFRAME (sel_frame)));
  1306.     }
  1307.     }
  1308. }
  1309.  
  1310. static Lisp_Object
  1311. cleanup_after_defocusing (Lisp_Object frm_and_dev)
  1312. {
  1313.   Lisp_Object frame = Fcar (frm_and_dev);
  1314.   Lisp_Object device = Fcdr (frm_and_dev);
  1315.  
  1316.   if (!DEVICE_LIVE_P (XDEVICE (device)))
  1317.     return Qnil;
  1318.   else
  1319.     {
  1320.       DEVICE_FRAME_WITH_FOCUS (XDEVICE (device)) = Qnil;
  1321.  
  1322.       if (FRAME_LIVE_P (XFRAME (frame)))
  1323.     redisplay_redraw_cursor (XFRAME (frame), 1);
  1324.     }
  1325.  
  1326.   return Qnil;
  1327. }
  1328.  
  1329. static Lisp_Object
  1330. cleanup_after_missed_defocusing (Lisp_Object frms_and_dev)
  1331. {
  1332.   Lisp_Object missed_frame = Fcar (frms_and_dev);
  1333.   Lisp_Object device = Fcar (Fcdr (frms_and_dev));
  1334.   Lisp_Object new_frame = Fcdr (Fcdr (frms_and_dev));
  1335.   struct device *d = XDEVICE (device);
  1336.  
  1337.   if (!DEVICE_LIVE_P (d))
  1338.     return Qnil;
  1339.  
  1340.   DEVICE_FRAME_WITH_FOCUS (d) = Qnil;
  1341.   redisplay_redraw_cursor (XFRAME (missed_frame), 1);
  1342.   if (!NILP (new_frame))
  1343.     {
  1344.       Fselect_frame (new_frame);
  1345.       DEVICE_FRAME_WITH_FOCUS (d) = new_frame;
  1346.       redisplay_redraw_cursor (XFRAME (new_frame), 1);
  1347.     }
  1348.   return Qnil;
  1349. }
  1350.  
  1351. /* Called from the window-system-specific code when we receive a
  1352.    notification that the focus lies on a particular frame. 
  1353.    Argument is a cons: (frame . in-p) where in-p is non-nil for focus-in.
  1354.  */
  1355. DEFUN ("emacs-handle-focus-change", Femacs_handle_focus_change,
  1356.        Semacs_handle_focus_change, 1, 1, 0,
  1357.   "internal function--don't call this.")
  1358.      (frame_inp_and_dev)
  1359.      Lisp_Object frame_inp_and_dev;
  1360. {
  1361.   Lisp_Object frame = Fcar (frame_inp_and_dev);
  1362.   Lisp_Object device = Fcar (Fcdr (frame_inp_and_dev));
  1363.   int in_p = !NILP (Fcdr (Fcdr (frame_inp_and_dev)));
  1364.   struct device *d;
  1365.   int count;
  1366.  
  1367.   if (!DEVICE_LIVE_P (XDEVICE (device)))
  1368.     return Qnil;
  1369.   else
  1370.     d = XDEVICE (device);
  1371.  
  1372.   /* Any received focus-change notifications render invalid any
  1373.      pending focus-change requests. */
  1374.   DEVICE_FRAME_THAT_OUGHT_TO_HAVE_FOCUS (d) = Qnil;
  1375.   if (in_p)
  1376.     {
  1377.       Lisp_Object focus_frame;
  1378.  
  1379.       if (!FRAME_LIVE_P (XFRAME (frame)))
  1380.     return Qnil;
  1381.       else
  1382.     focus_frame = DEVICE_FRAME_WITH_FOCUS (d);
  1383.  
  1384.       /* Mark the minibuffer as changed to make sure it gets updated
  1385.          properly if the echo area is active. */
  1386.       MARK_WINDOWS_CHANGED (XWINDOW (FRAME_MINIBUF_WINDOW (XFRAME (frame))));
  1387.  
  1388.       if (FRAMEP (focus_frame) && !EQ (frame, focus_frame))
  1389.     {
  1390.       Lisp_Object conser = Qnil;
  1391.       Lisp_Object conser2 = Qnil;
  1392.       struct gcpro gcpro1, gcpro2;
  1393.  
  1394.       GCPRO2 (conser, conser2);
  1395.       /* Oops, we missed a focus-out event. */
  1396.       Fselect_frame (focus_frame);
  1397.       /* Do an unwind-protect in case an error occurs in
  1398.          the deselect-frame-hook */
  1399.       count = specpdl_depth ();
  1400.       conser2 = Fcons (device, frame);
  1401.       conser = Fcons (focus_frame, conser2);
  1402.       record_unwind_protect (cleanup_after_missed_defocusing, conser);
  1403.       run_deselect_frame_hook ();
  1404.       /* No errors, so tell the cleanup method not to do the stuff
  1405.          we're going to do below anyway. */
  1406.       Fsetcdr (conser2, Qnil);
  1407.       unbind_to (count, Qnil);
  1408.       /* the cleanup method changed the focus frame to nil, so
  1409.          we need to reflect this */
  1410.       focus_frame = Qnil;
  1411.       UNGCPRO;
  1412.     }
  1413.       Fselect_frame (frame);
  1414.       DEVICE_FRAME_WITH_FOCUS (d) = frame;
  1415.       if (!EQ (frame, focus_frame))
  1416.     {
  1417.       redisplay_redraw_cursor (XFRAME (frame), 1);
  1418.       run_select_frame_hook ();
  1419.     }
  1420.     }
  1421.   else
  1422.     {
  1423.       /* We ignore the frame reported in the event.  If it's different
  1424.      from where we think the focus was, oh well -- we messed up.
  1425.      Nonetheless, we pretend we were right, for sensible behavior. */
  1426.       frame = DEVICE_FRAME_WITH_FOCUS (d);
  1427.       if (!NILP (frame))
  1428.     {
  1429.       Lisp_Object conser = Qnil;
  1430.       struct gcpro gcpro1;
  1431.  
  1432.       GCPRO1 (conser);
  1433.       /* Do an unwind-protect in case an error occurs in
  1434.          the deselect-frame-hook */
  1435.       count = specpdl_depth ();
  1436.       conser = Fcons (frame, device);
  1437.       record_unwind_protect (cleanup_after_defocusing, conser);
  1438.       run_deselect_frame_hook ();
  1439.       unbind_to (count, Qnil);
  1440.       UNGCPRO;
  1441.     }
  1442.     }
  1443.   return Qnil;
  1444. }
  1445.  
  1446.  
  1447. /**********************************************************************/
  1448. /*                      retrieving the next event                     */
  1449. /**********************************************************************/
  1450.  
  1451. /* the number of keyboard characters read.  callint.c wants this. 
  1452.  */
  1453. Charcount num_input_chars;
  1454.  
  1455. static void
  1456. next_event_internal (Lisp_Object target_event, int allow_queued)
  1457. {
  1458.   /* QUIT;   This is incorrect - the caller must do this because some
  1459.          callers (ie, Fnext_event()) do not want to QUIT. */
  1460.  
  1461.   assert (!event_next (XEVENT (target_event)));
  1462.  
  1463.   investigate_frame_change ();
  1464.     
  1465.   if (allow_queued && !NILP (command_event_queue))
  1466.     {
  1467.       Lisp_Object event = dequeue_command_event ();
  1468.       Fcopy_event (event, target_event);
  1469.       Fdeallocate_event (event);
  1470.     }
  1471.   else
  1472.     {
  1473.       struct Lisp_Event *e = XEVENT (target_event);
  1474.  
  1475.       /* The command_event_queue was empty.  Wait for an event. */
  1476.       event_stream_next_event (e);
  1477.       /* If this was a timeout, then we need to extract some data
  1478.      out of the returned closure and might need to resignal
  1479.      it. */
  1480.       if (e->event_type == timeout_event)
  1481.     {
  1482.       struct timeout *timeout =
  1483.         event_stream_resignal_wakeup (e->event.timeout.interval_id, 0);
  1484.       
  1485.       e->event.timeout.id_number = timeout->id;
  1486.       e->event.timeout.function = timeout->function;
  1487.       e->event.timeout.object = timeout->object;
  1488.     }
  1489.  
  1490.       /* If we read a ^G, then set quit-flag but do not discard the ^G.
  1491.      The callers of next_event_internal() will do one of two things:
  1492.  
  1493.      -- set Vquit_flag to Qnil. (next-event does this.) This will
  1494.         cause the ^G to be treated as a normal keystroke.
  1495.      -- not change Vquit_flag but attempt to enqueue the ^G, at
  1496.         which point it will be discarded.  The next time QUIT is
  1497.         called, it will notice that Vquit_flag was set.
  1498.  
  1499.        */
  1500.       if (e->event_type == key_press_event &&
  1501.       event_matches_key_specifier_p
  1502.       (e, make_number (DEVICE_QUIT_CHAR (XDEVICE (e->device)))))
  1503.     {
  1504.       Vquit_flag = Qt;
  1505.     }
  1506.     }
  1507. }
  1508.  
  1509. static void push_this_command_keys (Lisp_Object event);
  1510. static void push_recent_keys (Lisp_Object event);
  1511. static void execute_internal_event (Lisp_Object event);
  1512. static void execute_command_event (struct command_builder *,
  1513.                                    Lisp_Object event);
  1514.  
  1515. DEFUN ("next-event", Fnext_event, Snext_event, 0, 2, 0,
  1516.  "Return the next available event.\n\
  1517. Pass this object to `dispatch-event' to handle it.\n\
  1518. In most cases, you will want to use `next-command-event', which returns\n\
  1519. the next available \"user\" event (i.e. keypress, button-press,\n\
  1520. button-release, or menu selection) instead of this function.\n\
  1521. \n\
  1522. If EVENT is non-nil, it should be an event object and will be filled in\n\
  1523. and returned; otherwise a new event object will be created and returned.\n\
  1524. If PROMPT is non-nil, it should be a string and will be displayed in the\n\
  1525. echo area while this function is waiting for an event.\n\
  1526. \n\
  1527. The next available event will be\n\
  1528. \n\
  1529. -- any events in `unread-command-events' or `unread-command-event'; else\n\
  1530. -- the next event in the currently executing keyboard macro, if any; else\n\
  1531. -- an event queued by `enqueue-eval-event', if any; else\n\
  1532. -- the next available event from the window system or terminal driver.\n\
  1533. \n\
  1534. In the last case, this function will block until an event is available.\n\
  1535. \n\
  1536. The returned event will be one of the following types:\n\
  1537. \n\
  1538. -- a key-press event.\n\
  1539. -- a button-press or button-release event.\n\
  1540. -- a misc-user-event, meaning the user selected an item on a menu or used\n\
  1541.    the scrollbar.\n\
  1542. -- a process event, meaning that output from a subprocess is available.\n\
  1543. -- a timeout event, meaning that a timeout has elapsed.\n\
  1544. -- an eval event, which simply causes a function to be executed when the\n\
  1545.    event is dispatched.  Eval events are generated by `enqueue-eval-event'\n\
  1546.    or by certain other conditions happening.\n\
  1547. -- a magic event, indicating that some window-system-specific event\n\
  1548.    happened (such as an focus-change notification) that must be handled\n\
  1549.    synchronously with other events.  `dispatch-event' knows what to do with\n\
  1550.    these events.")
  1551.      (event, prompt)
  1552.      Lisp_Object event, prompt;
  1553. {
  1554.   /* This function can GC */
  1555.   struct command_builder *command_builder = the_command_builder;
  1556.   int store_this_key = 0;
  1557.   struct gcpro gcpro1;
  1558.   GCPRO1 (event);
  1559.  
  1560.   /* DO NOT do QUIT anywhere within this function or the functions it calls.
  1561.      We want to read the ^G as an event. */
  1562.  
  1563.   if (NILP (event))
  1564.     event = Fallocate_event ();
  1565.   else
  1566.     CHECK_LIVE_EVENT (event, 0);
  1567.  
  1568.   if (!NILP (prompt))
  1569.     {
  1570.       Bytecount len;
  1571.       CHECK_STRING (prompt, 1);
  1572.  
  1573.       len = string_length (XSTRING (prompt));
  1574.       if (command_builder->echo_buf_length < len)
  1575.     len = command_builder->echo_buf_length - 1;
  1576.       memcpy (command_builder->echo_buf, string_data (XSTRING (prompt)), len);
  1577.       command_builder->echo_buf[len] = 0;
  1578.       command_builder->echo_buf_index = len;
  1579.       command_builder->echo_esc_index = -1;
  1580.       echo_area_message (selected_frame (), the_command_builder->echo_buf,
  1581.              Qnil, 0,
  1582.              the_command_builder->echo_buf_index,
  1583.              Qcommand);
  1584.     }
  1585.  
  1586.   redisplay ();
  1587.  
  1588.   /* If there is something in unread-command-events, simply return it.
  1589.      But do some error checking to make sure the user hasn't put something
  1590.      in the unread-command-events that they shouldn't have.
  1591.      This does not update this-command-keys and recent-keys.
  1592.      */
  1593.   if (!NILP (Vunread_command_events))
  1594.     {
  1595.       if (!CONSP (Vunread_command_events))
  1596.     {
  1597.       Vunread_command_events = Qnil;
  1598.       signal_error (Qwrong_type_argument,
  1599.             list3 (Qconsp, Vunread_command_events,
  1600.                    Qunread_command_events));
  1601.     }
  1602.       else
  1603.     {
  1604.       Lisp_Object e = XCAR (Vunread_command_events);
  1605.       Vunread_command_events = XCDR (Vunread_command_events);
  1606.       if (!EVENTP (e) || !command_event_p (XEVENT (e)))
  1607.         signal_error (Qwrong_type_argument,
  1608.               list3 (Qeventp, e, Qunread_command_events));
  1609.       if (!EQ (e, event))
  1610.         Fcopy_event (e, event);
  1611.     }
  1612.     }
  1613.  
  1614.   /* Do similar for unread-command-event (obsoleteness support).
  1615.    */
  1616.   else if (!NILP (Vunread_command_event))
  1617.     {
  1618.       Lisp_Object e = Vunread_command_event;
  1619.       Vunread_command_event = Qnil;
  1620.       
  1621.       if (!EVENTP (e) || !command_event_p (XEVENT (e)))
  1622.     {
  1623.       signal_error (Qwrong_type_argument,
  1624.             list3 (Qeventp, e, Qunread_command_event));
  1625.     }
  1626.       if (!EQ (e, event))
  1627.     Fcopy_event (e, event);
  1628.     }
  1629.   
  1630.   /* If we're executing a keyboard macro, take the next event from that,
  1631.      and update this-command-keys and recent-keys.
  1632.      Note that the unread-command-events take precedence over kbd macros.
  1633.      */
  1634.   else if (!NILP (Vexecuting_macro))
  1635.     {
  1636.       pop_kbd_macro_event (event);  /* This throws past us at end-of-macro. */
  1637.       store_this_key = 1;
  1638.     }
  1639.   /* Otherwise, read a real event, possibly from the command_event_queue,
  1640.      and update this-command-keys and recent-keys.
  1641.      */
  1642.   else
  1643.     {
  1644.       next_event_internal (event, 1);
  1645.       Vquit_flag = Qnil; /* Read C-g as an event. */
  1646.       store_this_key = 1;
  1647.     }
  1648.  
  1649.   status_notify ();             /* Notice process change */
  1650.  
  1651. #ifdef C_ALLOCA
  1652.   alloca (0);        /* Cause a garbage collection now */
  1653.   /* Since we can free the most stuff here
  1654.    *  (since this is typically called from
  1655.    *  the command-loop top-level). */
  1656. #endif /* C_ALLOCA */
  1657.  
  1658.   switch (XEVENT (event)->event_type)
  1659.     {
  1660.     default:
  1661.       goto RETURN;
  1662.     case button_release_event:
  1663.     case misc_user_event:
  1664.       goto EXECUTE_KEY;
  1665.     case button_press_event:    /* key or mouse input can trigger prompting */
  1666.       goto STORE_AND_EXECUTE_KEY;
  1667.     case key_press_event:         /* any key input can trigger autosave */
  1668.       break;
  1669.     }
  1670.  
  1671.   maybe_do_auto_save ();
  1672.   num_input_chars++;
  1673.  STORE_AND_EXECUTE_KEY:
  1674.   if (store_this_key)
  1675.     echo_key_event (command_builder, event);
  1676.  
  1677.  EXECUTE_KEY:
  1678.   /* Store the last-input-event.  The semantics of this is that it is
  1679.      the thing most recently returned by next-command-event.  It need
  1680.      not have come from the keyboard or a keyboard macro, it may have
  1681.      come from unread-command-events.  It's always a command-event (a
  1682.      key, click, or menu selection), never a motion or process event.
  1683.      */
  1684.   if (!EVENTP (Vlast_input_event))
  1685.     Vlast_input_event = Fallocate_event ();
  1686.   if (XEVENT (Vlast_input_event)->event_type == dead_event)
  1687.     {
  1688.       Vlast_input_event = Fallocate_event ();
  1689.       error ("Someone deallocated last-input-event!");
  1690.     }
  1691.   if (! EQ (event, Vlast_input_event))
  1692.     Fcopy_event (event, Vlast_input_event);
  1693.       
  1694.   /* last-input-char and last-input-time are derived from
  1695.      last-input-event.
  1696.      Note that last-input-char will never have its high-bit set, in an
  1697.      effort to sidestep the ambiguity between M-x and oslash.
  1698.      */
  1699.   Vlast_input_char = Fevent_to_character (Vlast_input_event,
  1700.                                           Qnil, Qnil, Qnil);
  1701.   {
  1702.     EMACS_TIME t;
  1703.     EMACS_GET_TIME (t);
  1704.     if (!CONSP (Vlast_input_time))
  1705.       Vlast_input_time = Fcons (Qnil, Qnil);
  1706.     XCAR (Vlast_input_time)
  1707.       = make_number ((EMACS_SECS (t) >> 16) & 0xffff);
  1708.     XCDR (Vlast_input_time)
  1709.       = make_number ((EMACS_SECS (t) >> 0)  & 0xffff);
  1710.   }
  1711.  
  1712.   /* If this key came from the keyboard or from a keyboard macro, then
  1713.      it goes into the recent-keys and this-command-keys vectors.
  1714.      If this key came from the keyboard, and we're defining a keyboard
  1715.      macro, then it goes into the macro.
  1716.      */
  1717.   if (store_this_key)
  1718.     {
  1719.       push_this_command_keys (event);
  1720.       push_recent_keys (event);
  1721.       if (defining_kbd_macro && NILP (Vexecuting_macro))
  1722.     {
  1723.       if (!EVENTP (command_builder->current_events))
  1724.         finalize_kbd_macro_chars ();
  1725.       store_kbd_macro_event (event);
  1726.     }
  1727.     }
  1728.   /* If this is the help char and there is a help form, then execute the
  1729.      help form and swallow this character.  This is the only place where
  1730.      calling Fnext_event() can cause arbitrary lisp code to run.  Note
  1731.      that execute_help_form() calls Fnext_command_event(), which calls
  1732.      this function, as well as Fdispatch_event.
  1733.      */
  1734.   /* #### could cause QUIT! */
  1735.   if (!NILP (Vhelp_form) &&
  1736.       event_matches_key_specifier_p (XEVENT (event), Vhelp_char))
  1737.     execute_help_form (command_builder, event);
  1738.  
  1739.  RETURN:
  1740.   UNGCPRO;
  1741.   return (event);
  1742. }
  1743.  
  1744. DEFUN ("next-command-event", Fnext_command_event, Snext_command_event, 0, 2, 0,
  1745. "Return the next available \"user\" event.\n\
  1746. Pass this object to `dispatch-event' to handle it.\n\
  1747. \n\
  1748. If EVENT is non-nil, it should be an event object and will be filled in\n\
  1749. and returned; otherwise a new event object will be created and returned.\n\
  1750. If PROMPT is non-nil, it should be a string and will be displayed in the\n\
  1751. echo area while this function is waiting for an event.\n\
  1752. \n\
  1753. The event returned will be a keyboard, mouse press, or mouse release event.\n\
  1754. If there are non-command events available (mouse motion, sub-process output,\n\
  1755. etc) then these will be executed (with `dispatch-event') and discarded.  This\n\
  1756. function is provided as a convenience; it is equivalent to the lisp code\n\
  1757. \n\
  1758.     (while (progn\n\
  1759.          (next-event event prompt)\n\
  1760.              (not (or (key-press-event-p event)\n\
  1761.                       (button-press-event-p event)\n\
  1762.                       (button-release-event-p event)\n\
  1763.                       (misc-user-event-p event))))\n\
  1764.        (dispatch-event event))\n")
  1765.      (event, prompt)
  1766.     Lisp_Object event, prompt;
  1767. {
  1768.   /* This function can GC */
  1769.   struct gcpro gcpro1;
  1770.   GCPRO1 (event);
  1771.   maybe_echo_keys (the_command_builder, 0); /* #### This sucks bigtime */
  1772.   for (;;)
  1773.     {
  1774.       event = Fnext_event (event, prompt);
  1775.       if (command_event_p (XEVENT (event)))
  1776.         break;
  1777.       else
  1778.         execute_internal_event (event);
  1779.     }
  1780.   UNGCPRO;
  1781.   return (event);
  1782. }
  1783.  
  1784. static void
  1785. reset_current_events (struct command_builder *command_builder)
  1786. {
  1787.   Lisp_Object event = command_builder->current_events;
  1788.   command_builder->current_events = Qnil;
  1789.   command_builder->most_current_event = Qnil;
  1790.   command_builder->last_non_function_event = Qnil;
  1791.   if (EVENTP (event))
  1792.     {
  1793.       for (;;)
  1794.     {
  1795.       struct Lisp_Event *e = event_next (XEVENT (event));
  1796.       Fdeallocate_event (event);
  1797.       if (e == 0)
  1798.         break;
  1799.       XSETEVENT (event, e);
  1800.     }
  1801.     }
  1802. }
  1803.  
  1804. DEFUN ("discard-input", Fdiscard_input, Sdiscard_input, 0, 0, 0,
  1805.   "Discard any pending \"user\" events.\n\
  1806. Also cancel any kbd macro being defined.\n\
  1807. A user event is a key press, button press, button release, or\n\
  1808. \"other-user\" event (menu selection or scrollbar action).")
  1809.   ()
  1810. {
  1811.   /* This throws away user-input on the queue, but doesn't process any
  1812.      events.  Calling dispatch_event() here leads to a race condition.
  1813.    */
  1814.   Lisp_Object event = Fallocate_event ();
  1815.   struct Lisp_Event *e = XEVENT (event);
  1816.   struct Lisp_Event *head = 0;
  1817.   struct Lisp_Event *tail = 0;
  1818.   Lisp_Object oiq = Vinhibit_quit;
  1819.   struct gcpro gcpro1, gcpro2;
  1820.  
  1821.   /* next_event_internal() can cause arbitrary Lisp code to be evalled */
  1822.   GCPRO2 (event, oiq);
  1823.   Vinhibit_quit = Qt;
  1824.   /* If a macro was being defined then we have to mark the modeline
  1825.      has changed to ensure that it gets updated correctly. */
  1826.   if (defining_kbd_macro)
  1827.     MARK_MODELINE_CHANGED;
  1828.   defining_kbd_macro = 0;
  1829.   reset_current_events (the_command_builder);
  1830.  
  1831.   while (!NILP (command_event_queue)
  1832.          || event_stream_event_pending_p (1))
  1833.     {
  1834.       /* This will take stuff off the command_event_queue, or read it
  1835.      from the event_stream, but it will not block.
  1836.        */
  1837.       next_event_internal (event, 1);
  1838.       Vquit_flag = Qnil; /* Treat C-g as a user event (ignore it).
  1839.                 It is vitally important that we reset
  1840.                 Vquit_flag here.  Otherwise, if we're
  1841.                 reading from a TTY device,
  1842.                 maybe_read_quit_event() will notice
  1843.                 that C-g has been set and send us
  1844.                 another C-g.  That will cause us
  1845.                 to get right back here, and read
  1846.                 another C-g, ad infinitum ... */
  1847.  
  1848.       /* If the event is a user event, ignore it. */
  1849.       if (! command_event_p (e))
  1850.       {
  1851.         /* Otherwise, chain the event onto our list of events not to ignore,
  1852.            and keep reading until the queue is empty.  This does not mean
  1853.            that if a subprocess is generating an infinite amount of output,
  1854.            we will never terminate (*provided* that the behavior of
  1855.        next_event_cb() is correct -- see the comment in events.h),
  1856.        because this loop ends as soon as there are no more user events
  1857.        on the command_event_queue or event_stream.
  1858.            */
  1859.         Lisp_Object event2 = Fcopy_event (event, Qnil);
  1860.         struct Lisp_Event *e2 = XEVENT (event2);
  1861.  
  1862.         if (tail)
  1863.           set_event_next (tail, e2);
  1864.         else
  1865.           head = e2;
  1866.         tail = e2;
  1867.       }
  1868.     }
  1869.  
  1870.   if (!NILP (command_event_queue) || command_event_queue_tail)
  1871.     abort ();
  1872.  
  1873.   /* Now tack our chain of events back on to the front of the queue.
  1874.      Actually, since the queue is now drained, we can just replace it.
  1875.      The effect of this will be that we have deleted all user events
  1876.      from the input stream without changing the relative ordering of
  1877.      any other events.  (Some events may have been taken from the
  1878.      event_stream and added to the command_event_queue, however.)
  1879.  
  1880.      At this time, the command_event_queue will contain only eval_events.
  1881.    */
  1882.   if (head)
  1883.     {
  1884.       XSETEVENT (command_event_queue, head);
  1885.       command_event_queue_tail = tail;
  1886.     }
  1887.  
  1888.   Fdeallocate_event (event);
  1889.   UNGCPRO;
  1890.  
  1891.   Vinhibit_quit = oiq;
  1892.   return Qnil;
  1893. }
  1894.  
  1895.  
  1896. /**********************************************************************/
  1897. /*                     pausing until an action occurs                 */
  1898. /**********************************************************************/
  1899.  
  1900. /* #### Is (accept-process-output nil 3) supposed to be like (sleep-for 3)?
  1901.  */
  1902.  
  1903. DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
  1904.        0, 3, 0,
  1905.   "Allow any pending output from subprocesses to be read by Emacs.\n\
  1906. It is read into the process' buffers or given to their filter functions.\n\
  1907. Non-nil arg PROCESS means do not return until some output has been received\n\
  1908.  from PROCESS.\n\
  1909. If the second arg is non-nil, it is the maximum number of seconds to wait:\n\
  1910.  this function will return after that much time even if no input has arrived\n\
  1911.  from PROCESS.  This argument may be a float, meaning wait some fractional\n\
  1912.  part of a second.\n\
  1913. If the third arg is non-nil, it is a number of milliseconds that is added\n\
  1914.  to the second arg.  (This exists only for compatibility.)\n\
  1915. Return non-nil iff we received any output before the timeout expired.")
  1916.      (process, timeout_secs, timeout_msecs)
  1917.      Lisp_Object process, timeout_secs, timeout_msecs;
  1918. {
  1919.   /* This function can GC */
  1920.   struct gcpro gcpro1, gcpro2;
  1921.   Lisp_Object event = Qnil;
  1922.   int timeout_id = 0;
  1923.   Lisp_Object result = Qnil;
  1924.   struct buffer *old_buffer = current_buffer;
  1925.  
  1926.   /* We preserve the current buffer but nothing else.  If a focus
  1927.      change alters the selected window then the top level event loop
  1928.      will eventually alter current_buffer to match.  In the mean time
  1929.      we don't want to mess up whatever called this function. */
  1930.  
  1931.   if (!NILP (process))
  1932.     CHECK_PROCESS (process, 0);
  1933.  
  1934.   GCPRO2 (event, process);
  1935.  
  1936.   if (!NILP (process) && (!NILP (timeout_secs) || !NILP (timeout_msecs)))
  1937.     {
  1938.       unsigned long msecs = 0;
  1939.       if (!NILP (timeout_secs))
  1940.     msecs = lisp_number_to_milliseconds (timeout_secs, 1);
  1941.       if (!NILP (timeout_msecs))
  1942.     {
  1943.       CHECK_NATNUM (timeout_msecs, 0);
  1944.       msecs += XINT (timeout_msecs);
  1945.     }
  1946.       if (msecs)
  1947.     timeout_id = event_stream_generate_wakeup (msecs, 0, Qnil, Qnil, 0);
  1948.     }
  1949.  
  1950.   event = Fallocate_event ();
  1951.  
  1952.   while (!NILP (process)
  1953.      /* Calling detect_input_pending() is the wrong thing here, because
  1954.         that considers the Vunread_command_events and command_event_queue.
  1955.         We don't need to look at the command_event_queue because we are
  1956.         only interested in process events, which don't go on that.  In
  1957.         fact, we can't read from it anyway, because we put stuff on it.
  1958.  
  1959.         Note that event_stream->event_pending_p must be called in such
  1960.         a way that it says whether any events *of any kind* are ready,
  1961.         not just user events, or (accept-process-output nil) will fail
  1962.         to dispatch any process events that may be on the queue.  It is
  1963.         not clear to me that this is important, because the top-level
  1964.         loop will process it, and I don't think that there is ever a
  1965.         time when one calls accept-process-output with a nil argument
  1966.         and really need the processes to be handled.
  1967.       */
  1968.      || (!EQ (result, Qt) && event_stream_event_pending_p (0)))
  1969.     {
  1970.       QUIT;    /* next_event_internal() does not QUIT, so check for ^G
  1971.            before reading output from the process - this makes it
  1972.            less likely that the filter will actually be aborted.
  1973.          */
  1974.  
  1975.       next_event_internal (event, 0);
  1976.       /* If C-g was pressed while we were waiting, Vquit_flag got
  1977.      set and next_event_internal() also returns C-g.  When
  1978.      we enqueue the C-g below, it will get discarded.  The
  1979.      next time through, QUIT will be called and will signal a quit. */
  1980.       switch (XEVENT (event)->event_type)
  1981.     {
  1982.     case process_event:
  1983.       {
  1984.         if (EQ (XEVENT (event)->event.process.process, process))
  1985.           {
  1986.         process = Qnil;
  1987.         /* RMS's version always returns nil when proc is nil,
  1988.            and only returns t if input ever arrived on proc. */
  1989.         result = Qt;
  1990.           }
  1991.  
  1992.         execute_internal_event (event);
  1993.         break;
  1994.       }
  1995.     case timeout_event:
  1996.       {
  1997.         if (XEVENT (event)->event.timeout.id_number == timeout_id)
  1998.           {
  1999.         timeout_id = 0;
  2000.         process = Qnil; /* we're done */
  2001.           }
  2002.         else          /* a timeout that wasn't one we're waiting for */
  2003.               goto EXECTUTE_INTERNAL;
  2004.         break;
  2005.       }
  2006.     case pointer_motion_event:
  2007.     case magic_event:
  2008.           {
  2009.           EXECTUTE_INTERNAL:
  2010.             execute_internal_event (event);
  2011.             break;
  2012.           }
  2013.     default:
  2014.           {
  2015.             enqueue_command_event_1 (event);
  2016.             break;
  2017.       }
  2018.     }
  2019.     }
  2020.  
  2021.   /* If our timeout has not been signalled yet, disable it. */
  2022.   if (timeout_id)
  2023.     event_stream_disable_wakeup (timeout_id, 0);
  2024.  
  2025.   Fdeallocate_event (event);
  2026.   UNGCPRO;
  2027.   current_buffer = old_buffer;
  2028.   return result;
  2029. }
  2030.  
  2031. DEFUN ("sleep-for", Fsleep_for, Ssleep_for, 1, 1, 0,
  2032.   "Pause, without updating display, for ARG seconds.\n\
  2033. ARG may be a float, meaning pause for some fractional part of a second.")
  2034.   (seconds)
  2035.      Lisp_Object seconds;
  2036. {
  2037.   /* This function can GC */
  2038.   unsigned long msecs = lisp_number_to_milliseconds (seconds, 1);
  2039.   int id;
  2040.   Lisp_Object event = Qnil;
  2041.   struct gcpro gcpro1;
  2042.  
  2043.   GCPRO1 (event);
  2044.  
  2045.   id = event_stream_generate_wakeup (msecs, 0, Qnil, Qnil, 0);
  2046.   event = Fallocate_event ();
  2047.   while (1)
  2048.     {
  2049.       QUIT;    /* next_event_internal() does not QUIT, so check for ^G
  2050.            before reading output from the process - this makes it
  2051.            less likely that the filter will actually be aborted.
  2052.          */
  2053.       /* We're a generator of the command_event_queue, so we can't be a
  2054.      consumer as well.  We don't care about command and eval-events
  2055.      anyway.
  2056.        */
  2057.       next_event_internal (event, 0); /* blocks */
  2058.       /* See the comment in accept-process-output about Vquit_flag */
  2059.       switch (XEVENT (event)->event_type)
  2060.     {
  2061.     case timeout_event:
  2062.       {
  2063.         if (XEVENT (event)->event.timeout.id_number == id)
  2064.           goto DONE_LABEL;
  2065.             else
  2066.               goto EXECUTE_INTERNAL;
  2067.       }
  2068.     case pointer_motion_event:
  2069.     case process_event:
  2070.     case magic_event:
  2071.           {
  2072.           EXECUTE_INTERNAL:
  2073.             execute_internal_event (event);
  2074.             break;
  2075.           }
  2076.     default:
  2077.       {
  2078.         enqueue_command_event_1 (event);
  2079.             break;
  2080.           }
  2081.     }
  2082.     }
  2083.  DONE_LABEL:
  2084.   Fdeallocate_event (event);
  2085.   UNGCPRO;
  2086.   return Qnil;
  2087. }
  2088.  
  2089. DEFUN ("sit-for", Fsit_for, Ssit_for, 1, 2, 0,
  2090.   "Perform redisplay, then wait ARG seconds or until user input is available.\n\
  2091. ARG may be a float, meaning a fractional part of a second.\n\
  2092. Optional second arg non-nil means don't redisplay, just wait for input.\n\
  2093. Redisplay is preempted as always if user input arrives, and does not\n\
  2094. happen if input is available before it starts.\n\
  2095. Value is t if waited the full time with no input arriving.")
  2096.   (seconds, nodisplay)
  2097.      Lisp_Object seconds, nodisplay;
  2098. {
  2099.   /* This function can GC */
  2100.   unsigned long msecs = lisp_number_to_milliseconds (seconds, 1);
  2101.   Lisp_Object event, result;
  2102.   struct Lisp_Event *e;
  2103.   struct gcpro gcpro1;
  2104.   int id;
  2105.  
  2106.   /* The unread-command-events count as pending input */
  2107.   if (!NILP (Vunread_command_events) || !NILP (Vunread_command_event))
  2108.     return Qnil;
  2109.  
  2110.   /* If the command-builder already has user-input on it (not eval events)
  2111.      then that means we're done too.
  2112.    */
  2113.   if (!NILP (command_event_queue))
  2114.     {
  2115.       for (e = XEVENT (command_event_queue); e; e = event_next (e))
  2116.       {
  2117.         if (command_event_p (e))
  2118.           return (Qnil);
  2119.       }
  2120.     }
  2121.  
  2122.   /* If we're in a macro, or noninteractive, or early in temacs, then
  2123.      don't wait. */
  2124.   if (noninteractive || !NILP (Vexecuting_macro))
  2125.     return (Qt);
  2126.  
  2127.   /* Otherwise, start reading events from the event_stream.
  2128.      Do this loop at least once even if (sit-for 0) so that we
  2129.      redisplay when no input pending.
  2130.    */
  2131.   event = Fallocate_event ();
  2132.   GCPRO1 (event);
  2133.  
  2134.   /* Generate the wakeup even if MSECS is 0, so that existing timeout/etc.
  2135.      events get processed.  The old (pre-19.12) code special-cased this
  2136.      and didn't generate a wakeup, but the resulting behavior was less than
  2137.      ideal; viz. the occurrence of (sit-for 0.001) scattered throughout
  2138.      the E-Lisp universe. */
  2139.  
  2140.   id = event_stream_generate_wakeup (msecs, 0, Qnil, Qnil, 0);
  2141.  
  2142.   while (1)
  2143.     {
  2144.       /* If there is no user input pending, then redisplay.
  2145.        */
  2146.       if (!event_stream_event_pending_p (1) && NILP (nodisplay))
  2147.     redisplay ();
  2148.  
  2149.       /* If we're no longer waiting for a timeout, bug out. */
  2150.       if (! id)
  2151.     {
  2152.       result = Qt;
  2153.       goto DONE_LABEL;
  2154.     }
  2155.  
  2156.       QUIT;    /* next_event_internal() does not QUIT, so check for ^G
  2157.            before reading output from the process - this makes it
  2158.            less likely that the filter will actually be aborted.
  2159.          */
  2160.       /* We're a generator of the command_event_queue, so we can't be a
  2161.      consumer as well.  In fact, we know there's nothing on the
  2162.      command_event_queue that we didn't just put there.
  2163.        */
  2164.       next_event_internal (event, 0); /* blocks */
  2165.       /* See the comment in accept-process-output about Vquit_flag */
  2166.  
  2167.       if (command_event_p (XEVENT (event)))
  2168.     {
  2169.       result = Qnil;
  2170.       goto DONE_LABEL;
  2171.     }
  2172.       switch (XEVENT (event)->event_type)
  2173.     {
  2174.     case eval_event:
  2175.       {
  2176.         /* eval-events get delayed until later. */
  2177.         enqueue_command_event (Fcopy_event (event, Qnil));
  2178.         break;
  2179.       }
  2180.     case timeout_event:
  2181.       {
  2182.         if (XEVENT (event)->event.timeout.id_number != id)
  2183.           /* a timeout that wasn't the one we're waiting for */
  2184.           goto EXECUTE_INTERNAL;
  2185.         id = 0;    /* assert that we are no longer waiting for it. */
  2186.         result = Qt;
  2187.         goto DONE_LABEL;
  2188.       }
  2189.       default:
  2190.       {
  2191.       EXECUTE_INTERNAL:
  2192.         execute_internal_event (event);
  2193.         break;
  2194.       }
  2195.     }
  2196.     }
  2197.  
  2198.  DONE_LABEL:
  2199.   /* If our timeout has not been signalled yet, disable it. */
  2200.   if (id)
  2201.     event_stream_disable_wakeup (id, 0);
  2202.  
  2203.   /* Put back the event (if any) that made Fsit_for() exit before the
  2204.      timeout.  Note that it is being added to the back of the queue, which
  2205.      would be inappropriate if there were any user events on the queue
  2206.      already: we would be misordering them.  But we know that there are
  2207.      no user-events on the queue, or else we would not have reached this
  2208.      point at all.
  2209.    */
  2210.   if (NILP (result))
  2211.     enqueue_command_event (event);
  2212.   else
  2213.     Fdeallocate_event (event);
  2214.  
  2215.   UNGCPRO;
  2216.   return (result);
  2217. }
  2218.  
  2219. /* This handy little function is used by xselect.c and energize.c to
  2220.    wait for replies from processes that aren't really processes (that is,
  2221.    the X server and the Energize server).
  2222.  */
  2223. void
  2224. wait_delaying_user_input (int (*predicate) (void *arg), void *predicate_arg)
  2225. {
  2226.   /* This function can GC */
  2227.   Lisp_Object event = Fallocate_event ();
  2228.   struct gcpro gcpro1;
  2229.   GCPRO1 (event);
  2230.  
  2231.   while (!(*predicate) (predicate_arg))
  2232.     {
  2233.       QUIT; /* next_event_internal() does not QUIT. */
  2234.  
  2235.       /* We're a generator of the command_event_queue, so we can't be a
  2236.      consumer as well.  Also, we have no reason to consult the
  2237.      command_event_queue; there are only user and eval-events there,
  2238.      and we'd just have to put them back anyway.
  2239.        */
  2240.       next_event_internal (event, 0);
  2241.       /* See the comment in accept-process-output about Vquit_flag */
  2242.       if (command_event_p (XEVENT (event))
  2243.           || (XEVENT (event)->event_type == eval_event))
  2244.         enqueue_command_event_1 (event);
  2245.       else
  2246.         execute_internal_event (event);
  2247.     }
  2248.   UNGCPRO;
  2249. }
  2250.  
  2251.  
  2252. /**********************************************************************/
  2253. /*                dispatching events; command builder                 */
  2254. /**********************************************************************/
  2255.  
  2256. static void
  2257. execute_internal_event (Lisp_Object event)
  2258. {
  2259.   /* This function can GC */
  2260.   switch (XEVENT (event)->event_type) 
  2261.     {
  2262.     case eval_event:
  2263.       {
  2264.     call1 (XEVENT (event)->event.eval.function, 
  2265.            XEVENT (event)->event.eval.object);
  2266.     return;
  2267.       }
  2268.     case pointer_motion_event:
  2269.       {
  2270.     /* events on dead frames get silently eaten */
  2271.     if (!FRAME_LIVE_P (XFRAME (XEVENT (event)->channel)))
  2272.       return;
  2273.     if (!NILP (Vmouse_motion_handler))
  2274.       call1 (Vmouse_motion_handler, event);
  2275.     return;
  2276.       }
  2277.  
  2278.     case process_event:
  2279.       {
  2280.     Lisp_Object p = XEVENT (event)->event.process.process;
  2281.     Charcount readstatus;
  2282.  
  2283.     assert  (PROCESSP (p));
  2284.     while ((readstatus = read_process_output (p)) > 0)
  2285.       ;
  2286.     if (readstatus > 0)
  2287.       ; /* this clauses never gets executed but allows the #ifdefs
  2288.            to work cleanly. */
  2289. #ifdef EWOULDBLOCK
  2290.     else if (readstatus == -1 && errno == EWOULDBLOCK)
  2291.       ;
  2292. #endif /* EWOULDBLOCK */
  2293. #ifdef EAGAIN
  2294.     else if (readstatus == -1 && errno == EAGAIN)
  2295.       ;
  2296. #endif /* EAGAIN */
  2297.     else if ((readstatus == 0 && 
  2298.           /* Note that we cannot distinguish between no input
  2299.              available now and a closed pipe.
  2300.              With luck, a closed pipe will be accompanied by
  2301.              subprocess termination and SIGCHLD.  */
  2302.           (!network_connection_p (p) ||
  2303.            /*
  2304.               When connected to ToolTalk (i.e.
  2305.               connected_via_filedesc_p()), it's not possible to
  2306.               reliably determine whether there is a message
  2307.               waiting for ToolTalk to receive.  ToolTalk expects
  2308.               to have tt_message_receive() called exactly once
  2309.               every time the file descriptor becomes active, so
  2310.               the filter function forces this by returning 0.
  2311.               Emacs must not interpret this as a closed pipe. */
  2312.            connected_via_filedesc_p (XPROCESS (p))))
  2313. #ifdef HAVE_PTYS
  2314.          /* On some OSs with ptys, when the process on one end of
  2315.             a pty exits, the other end gets an error reading with
  2316.             errno = EIO instead of getting an EOF (0 bytes read).
  2317.             Therefore, if we get an error reading and errno =
  2318.             EIO, just continue, because the child process has
  2319.             exited and should clean itself up soon (e.g. when we
  2320.             get a SIGCHLD). */
  2321.          || (readstatus == -1 && errno == EIO)
  2322. #endif
  2323.          )
  2324.       {
  2325.         /* Currently, we rely on SIGCHLD to indicate that
  2326.            the process has terminated.  Unfortunately, it
  2327.            appears that on some systems the SIGCHLD gets
  2328.            missed some of the time.  So, we put in am
  2329.            additional check in status_notify() to see
  2330.            whether a process has terminated.  We have to
  2331.            tell status_notify() to enable that check, and
  2332.            we do so now. */
  2333.         kick_status_notify ();
  2334.       }
  2335.     else
  2336.       {
  2337.         /* Deactivate network connection */
  2338.         Lisp_Object status = Fprocess_status (p);
  2339.         if (EQ (status, Qopen)
  2340.         /* In case somebody changes the theory of whether to
  2341.            return open as opposed to run for network connection
  2342.            "processes"... */
  2343.         || EQ (status, Qrun))
  2344.           update_process_status (p, Qexit, 256, 0);
  2345.         deactivate_process (p);
  2346.       }
  2347.  
  2348.     /* We must call status_notify here to allow the
  2349.        event_stream->unselect_process_cb to be run if appropriate.
  2350.        Otherwise, dead fds may be selected for, and we will get a
  2351.        continuous stream of process events for them.  Since we don't
  2352.        return until all process events have been flushed, we would
  2353.        get stuck here, processing events on a process whose status
  2354.        was 'exit.  Call this after dispatch-event, or the fds will
  2355.        have been closed before we read the last data from them.
  2356.        It's safe for the filter to signal an error because
  2357.        status_notify() will be called on return to top-level.
  2358.        */
  2359.     status_notify ();
  2360.     return;
  2361.       }
  2362.  
  2363.     case timeout_event:
  2364.       {
  2365.     struct Lisp_Event *e = XEVENT (event);
  2366.     if (!NILP (e->event.timeout.function))
  2367.       call1 (e->event.timeout.function,
  2368.          e->event.timeout.object);
  2369.     return;
  2370.       }
  2371.     case magic_event:
  2372.       {
  2373.     event_stream_handle_magic_event (XEVENT (event));
  2374.     return;
  2375.       }
  2376.     default:
  2377.       abort ();
  2378.     }
  2379. }
  2380.  
  2381.  
  2382.  
  2383. /* If we read extra events attempting to match a function key but end
  2384.    up failing, then we release those events back to the command loop
  2385.    and fail on the original lookup.  The released events will then be
  2386.    reprocessed in the context of the first part having failed. */
  2387. static void
  2388. repush_function_events (struct command_builder *command_builder)
  2389. {
  2390.   Lisp_Object event0;
  2391.   struct Lisp_Event *event_h, *event_t;
  2392.  
  2393.   event0 = command_builder->last_non_function_event;
  2394.  
  2395.   if (NILP (event0))
  2396.     return;
  2397.  
  2398.   if (event_next (XEVENT (event0)) == 0)
  2399.     return;
  2400.   else
  2401.     event_h = event_next (XEVENT (event0));
  2402.  
  2403.   for (event_t = event_h;
  2404.        event_next (event_t);
  2405.        event_t = event_next (event_t))
  2406.     ;
  2407.  
  2408.   /* Put the commands back on the event queue. */
  2409.   if (NILP (command_event_queue))
  2410.     {
  2411.       set_event_next (event_t, 0);
  2412.       command_event_queue_tail = event_t;
  2413.     }
  2414.   else
  2415.     {
  2416.       struct Lisp_Event *e = XEVENT (command_event_queue);
  2417.       set_event_next (event_t, e);
  2418.     }
  2419.   XSETEVENT (command_event_queue, event_h);
  2420.  
  2421.   /* Then remove them from the command builder. */
  2422.   set_event_next (XEVENT (event0), 0);
  2423.   command_builder->most_current_event = event0;
  2424.   command_builder->last_non_function_event = Qnil;
  2425. }
  2426.  
  2427. /* Compare the current state of the command builder against the local and
  2428.    global keymaps; if there is no match, try again, case-insensitively.
  2429.    The binding found (if any) is returned.
  2430.    It may be a command or a keymap if we're not done yet.
  2431.  */
  2432. static Lisp_Object
  2433. command_builder_find_leaf (struct command_builder *command_builder,
  2434.                            int allow_misc_user_events_p)
  2435. {
  2436.   /* This function can GC */
  2437.   Lisp_Object event0 = command_builder->current_events;
  2438.   Lisp_Object result;
  2439.   struct Lisp_Event *terminal;
  2440.  
  2441.   if (NILP (event0))
  2442.     return (Qnil);
  2443.  
  2444.   if (allow_misc_user_events_p 
  2445.       && (event_next (XEVENT (event0)) == 0)
  2446.       && (XEVENT (event0)->event_type == misc_user_event))
  2447.     {
  2448.       Lisp_Object fn = XEVENT (event0)->event.eval.function;
  2449.       Lisp_Object arg = XEVENT (event0)->event.eval.object;
  2450.       return (list2 (fn, arg));
  2451.     }
  2452.  
  2453.   result = event_binding (event0, 1);
  2454.   if (!NILP (result))
  2455.     {
  2456.       Lisp_Object map;
  2457.       /* The suppress-keymap function binds keys to 'undefined - special-case
  2458.      that here, so that being bound to that has the same error-behavior as
  2459.      not being defined at all.
  2460.      */
  2461.       if (EQ (result, Qundefined))
  2462.     return (Qnil);
  2463.       /* Snap out possible keymap indirections */
  2464.       map = get_keymap (result, 0, 1);
  2465.       if (!NILP (map))
  2466.     return (map);
  2467.       return (result);
  2468.     }
  2469.  
  2470.   /* Check to see if we have a potential function key map match. */
  2471.   /* #### This should really work by scanning backwards to find and
  2472.      replace suffixes.  In practice this might actually be
  2473.      sufficient. */
  2474.   {
  2475.     result = function_key_map_event_binding (event0);
  2476.  
  2477.     if (NILP (result) || EQ (result, Qundefined))
  2478.       {
  2479.     if (!NILP (command_builder->last_non_function_event))
  2480.       repush_function_events (command_builder);
  2481.     /* drop through and continue */
  2482.       }
  2483.     else
  2484.       {
  2485.     Lisp_Object map;
  2486.  
  2487.     if (NILP (command_builder->last_non_function_event))
  2488.       {
  2489.         for (terminal = XEVENT (event0);
  2490.          event_next (terminal);
  2491.          terminal = event_next (terminal))
  2492.           ;
  2493.  
  2494.         XSETEVENT (command_builder->last_non_function_event, terminal);
  2495.       }
  2496.  
  2497.     map = get_keymap (result, 0, 1);
  2498.     if (!NILP (map))
  2499.       return (map);
  2500.  
  2501.     /* #### There are other results such as vectors which we
  2502.            should also be able to deal with. */
  2503.     if (SYMBOLP (result))
  2504.       {
  2505.         Lisp_Object event = Qnil;
  2506.         struct Lisp_Event *e;
  2507.  
  2508.         if (event_next (XEVENT (event0)))
  2509.           XSETEVENT (event, event_next (XEVENT (event0)));
  2510.         if (!NILP (event) && EVENTP (event))
  2511.           {
  2512.         for (;;)
  2513.           {
  2514.             e = event_next (XEVENT (event));
  2515.             Fdeallocate_event (event);
  2516.             if (e == 0)
  2517.               break;
  2518.             XSETEVENT (event, e);
  2519.           }
  2520.           }
  2521.  
  2522.         e = XEVENT (event0);
  2523.         e->event.key.modifiers = 0;
  2524.         e->event.key.keysym = result;
  2525.         e->next = 0;
  2526.  
  2527.         command_builder->last_non_function_event = Qnil;
  2528.         return (command_builder_find_leaf (command_builder,
  2529.                            allow_misc_user_events_p));
  2530.       }
  2531.     else
  2532.       {
  2533.         if (!NILP (command_builder->last_non_function_event))
  2534.           repush_function_events (command_builder);
  2535.         /* drop through and continue */
  2536.       }
  2537.       }
  2538.   }
  2539.       
  2540.   /* If we didn't find a binding, and the last event in the sequence is
  2541.      a shifted character, then try again with the lowercase version.  */
  2542.   for (terminal = XEVENT (event0);
  2543.        event_next (terminal);
  2544.        terminal = event_next (terminal))
  2545.     ;
  2546.  
  2547.   /* If key-sequence wasn't bound, we'll try some fallbacks.  */
  2548.  
  2549.   if (!NILP (Vretry_undefined_key_binding_unshifted)
  2550.       && terminal->event_type == key_press_event
  2551.       && ((terminal->event.key.modifiers & MOD_SHIFT)
  2552.           || (INTP (terminal->event.key.keysym)
  2553.               && XINT (terminal->event.key.keysym) >= 'A'
  2554.               && XINT (terminal->event.key.keysym) <= 'Z')))
  2555.       {
  2556.     struct Lisp_Event terminal_copy;
  2557.     terminal_copy = *terminal;
  2558.  
  2559.     if (terminal->event.key.modifiers & MOD_SHIFT)
  2560.       terminal->event.key.modifiers &= (~ MOD_SHIFT);
  2561.     else
  2562.       terminal->event.key.keysym
  2563.             = make_number (XINT (terminal->event.key.keysym) + 'a' - 'A');
  2564.  
  2565.     result = command_builder_find_leaf (command_builder,
  2566.                                             allow_misc_user_events_p);
  2567.     if (!NILP (result))
  2568.       return (result);
  2569.     /* If there was no match with the lower-case version either, then
  2570.        put back the upper-case event for the error message. */
  2571.     *terminal = terminal_copy;
  2572.       }
  2573.  
  2574.   if (!NILP (Vprefix_help_command) &&
  2575.       event_matches_key_specifier_p (terminal, Vhelp_char))
  2576.   {
  2577.     return (Vprefix_help_command);
  2578.   }
  2579.  
  2580.   return (Qnil);
  2581. }
  2582.  
  2583.  
  2584. /* Every time a command-event (a key, button, or menu selection) is read by
  2585.    Fnext_event(), it is stored in the recent_keys_ring, in Vlast_input_event,
  2586.    and in Vthis_command_keys.  (Eval-events are not stored there.)
  2587.  
  2588.    Every time a command is invoked, Vlast_command_event is set to the last
  2589.    event in the sequence.
  2590.  
  2591.    This means that Vthis_command_keys is really about "input read since the
  2592.    last command was executed" rather than about "what keys invoked this
  2593.    command."  This is a little counterintuitive, but that's the way it 
  2594.    has always worked.
  2595.  
  2596.    As an extra kink, the function read-key-sequence resets/updates the
  2597.    last-command-event and this-command-keys.  It doesn't append to the
  2598.    command-keys as read-char does.  Such are the pitfalls of having to
  2599.    maintain compatibility with a program for which the only specification
  2600.    is the code itself.
  2601.  
  2602.    (We could implement recent_keys_ring and Vthis_command_keys as the same
  2603.    data structure.)
  2604.  */
  2605.  
  2606. #define RECENT_KEYS_SIZE 100
  2607. Lisp_Object recent_keys_ring;
  2608. int recent_keys_ring_index;
  2609.  
  2610. DEFUN ("recent-keys", Frecent_keys, Srecent_keys, 0, 0, 0,
  2611.   "Return vector of last 100 or so keyboard or mouse button events read.\n\
  2612. This copies the event objects into a new vector; it is safe to keep and\n\
  2613. modify them.")
  2614.   ()
  2615. {
  2616.   struct gcpro gcpro1;
  2617.   Lisp_Object val = Qnil;
  2618.   int size = XVECTOR (recent_keys_ring)->size;
  2619.   int start, nkeys, i, j;
  2620.   GCPRO1 (val);
  2621.  
  2622.   if (NILP (vector_data (XVECTOR (recent_keys_ring))[recent_keys_ring_index]))
  2623.     /* This means the vector has not yet wrapped */
  2624.     {
  2625.       nkeys = recent_keys_ring_index;
  2626.       start = 0;
  2627.     }
  2628.   else
  2629.     {
  2630.       nkeys = size;
  2631.       start = ((recent_keys_ring_index == size) ? 0 : recent_keys_ring_index);
  2632.     }
  2633.  
  2634.   val = make_vector (nkeys, Qnil);
  2635.  
  2636.   for (i = 0, j = start; i < nkeys; i++)
  2637.   {
  2638.     Lisp_Object e = vector_data (XVECTOR (recent_keys_ring))[j];
  2639.  
  2640.     if (NILP (e))
  2641.       abort ();
  2642.     vector_data (XVECTOR (val))[i] = Fcopy_event (e, Qnil);
  2643.     if (++j >= size)
  2644.       j = 0;
  2645.   }
  2646.   UNGCPRO;
  2647.   return (val);
  2648. }
  2649.  
  2650.  
  2651. /* An event (actually an event chain linked through event_next) or Qnil.
  2652.    This is stored reversed, with the most recent (copied) event as the
  2653.    head of the chain. */
  2654. Lisp_Object Vthis_command_keys;
  2655.  
  2656. /* Vthis_command_keys having value Qnil means that the next time
  2657.    push_this_command_keys is called, it should start over.
  2658.    The times at which the the command-keys are reset
  2659.    (instead of merely being augumented) are pretty conterintuitive.
  2660.  */
  2661. Lisp_Object
  2662. reset_this_command_keys (Lisp_Object reset_echo)
  2663. {
  2664.   Lisp_Object e = Vthis_command_keys;
  2665.  
  2666.   if (!NILP (reset_echo))
  2667.     reset_key_echo (the_command_builder, 1);
  2668.  
  2669.   if (NILP (e))
  2670.     return (Qnil);
  2671.  
  2672.   for (;;)
  2673.     {
  2674.       struct Lisp_Event *n = event_next (XEVENT (e));
  2675.  
  2676.       Fdeallocate_event (e);
  2677.       if (!n)
  2678.     {
  2679.       Vthis_command_keys = Qnil;
  2680.       return (Qnil);
  2681.     }
  2682.       XSETEVENT (e, n);
  2683.     }
  2684. }
  2685.  
  2686. static void
  2687. push_this_command_keys (Lisp_Object event)
  2688. {
  2689.   Lisp_Object new = Fallocate_event ();
  2690.  
  2691.   Fcopy_event (event, new);
  2692.   set_event_next (XEVENT (new),
  2693.           ((!NILP (Vthis_command_keys))
  2694.            ? XEVENT (Vthis_command_keys)
  2695.            : 0));
  2696.   Vthis_command_keys = new;
  2697. }
  2698.  
  2699. static void
  2700. push_recent_keys (Lisp_Object event)
  2701. {
  2702.   Lisp_Object e
  2703.     = vector_data (XVECTOR (recent_keys_ring)) [recent_keys_ring_index];
  2704.  
  2705.   if (NILP (e))
  2706.     {
  2707.       e = Fallocate_event ();
  2708.       vector_data (XVECTOR (recent_keys_ring)) [recent_keys_ring_index] = e;
  2709.     }
  2710.   Fcopy_event (event, e);
  2711.   if (++recent_keys_ring_index == XVECTOR (recent_keys_ring)->size)
  2712.     recent_keys_ring_index = 0;
  2713. }
  2714.  
  2715.  
  2716. static Lisp_Object
  2717. current_events_into_vector (struct command_builder *command_builder)
  2718. {
  2719.   Lisp_Object vector;
  2720.   struct Lisp_Event *e;
  2721.   int n;
  2722.  
  2723.   for (e = XEVENT (command_builder->current_events), n = 0;
  2724.        e;
  2725.        e = event_next (e), n++)
  2726.     ;
  2727.   /* Copy the vector and the events in it. */
  2728.   /*  No need to copy the events, since they're already copies, and
  2729.       nobody other than the command-builder has pointers to them */
  2730.   vector = make_vector (n, Qnil);
  2731.   for (e = XEVENT (command_builder->current_events), n = 0;
  2732.        e;
  2733.        e = event_next (e), n++)
  2734.     XSETEVENT (vector_data (XVECTOR (vector))[n], e);
  2735.   command_builder->current_events = Qnil;
  2736.   command_builder->most_current_event = Qnil;
  2737.   command_builder->last_non_function_event = Qnil;
  2738.   return (vector);
  2739. }
  2740.  
  2741.  
  2742. /* Do command-loop book-keeping for keypresses, mouse-buttons
  2743.  * and menu-events */
  2744. static Lisp_Object
  2745. lookup_command_event (struct command_builder *command_builder,
  2746.                       Lisp_Object event, int allow_misc_user_events_p)
  2747. {
  2748.   /* This function can GC */
  2749.   struct frame *f = selected_frame ();
  2750.   /* Clear output from previous command execution */
  2751.   if (!EQ (Qcommand, echo_area_status (f))
  2752.       /* but don't let mouse-up clear what mouse-down just printed */
  2753.       && (XEVENT (event)->event_type != button_release_event))
  2754.     clear_echo_area (f, Qnil, 0);
  2755.  
  2756.   /* Add the given event to the command builder, enlarging the vector 
  2757.      first if necessary.
  2758.      Extra hack: this also updates the recent_keys_ring and Vthis_command_keys
  2759.      vectors to translate "ESC x" to "M-x" (for any "x" of course).
  2760.      */
  2761.   {
  2762.     Lisp_Object recent = command_builder->most_current_event;
  2763.  
  2764.     if (EVENTP (recent)
  2765.     && event_matches_key_specifier_p (XEVENT (recent), Vmeta_prefix_char))
  2766.       {
  2767.     struct Lisp_Event *e;
  2768.     /* When we see a sequence like "ESC x", pretend we really saw "M-x".
  2769.        DoubleThink the recent-keys and this-command-keys as well. */
  2770.  
  2771.     /* Modify the previous most-recently-pushed event on the command
  2772.        builder to be a copy of this one with the meta-bit set instead of
  2773.        pushing a new event.
  2774.        */
  2775.     Fcopy_event (event, recent);
  2776.     e = XEVENT (recent);
  2777.     if (e->event_type == key_press_event)
  2778.       e->event.key.modifiers |= MOD_META;
  2779.     else if (e->event_type == button_press_event 
  2780.          || e->event_type == button_release_event)
  2781.       e->event.button.modifiers |= MOD_META;
  2782.     else
  2783.       abort ();
  2784.  
  2785.     if (command_builder->echo_esc_index >= 0)
  2786.       {
  2787.         /* regenerate the final echo-glyph */
  2788.         command_builder->echo_buf_index = command_builder->echo_esc_index;
  2789.         echo_key_event (command_builder, recent);
  2790.         command_builder->echo_esc_index = -1;
  2791.       }
  2792.       }
  2793.     else
  2794.       {
  2795.     event = Fcopy_event (event, Fallocate_event ());
  2796.  
  2797.     if (EVENTP (recent))
  2798.       set_event_next (XEVENT (recent), XEVENT (event));
  2799.     else
  2800.       command_builder->current_events = event;
  2801.  
  2802.     command_builder->most_current_event = event;
  2803.       }
  2804.   }
  2805.  
  2806.   {
  2807.     Lisp_Object leaf = command_builder_find_leaf (command_builder,
  2808.                                                   allow_misc_user_events_p);
  2809.     struct gcpro gcpro1;
  2810.     GCPRO1 (leaf);
  2811.  
  2812.     if (KEYMAPP (leaf))
  2813.       {
  2814.     Lisp_Object prompt = Fkeymap_prompt (leaf, Qt);
  2815.     if (STRINGP (prompt))
  2816.       {
  2817.         /* Append keymap prompt to key echo buffer */
  2818.         int buf_index = command_builder->echo_buf_index;
  2819.         int len = string_length (XSTRING (prompt));
  2820.  
  2821.         if (len + buf_index + 1 <= command_builder->echo_buf_length)
  2822.           {
  2823.         Bufbyte *echo = command_builder->echo_buf + buf_index;
  2824.         memcpy (echo, string_data (XSTRING (prompt)), len);
  2825.         echo[len] = 0;
  2826.           }
  2827.         maybe_echo_keys (command_builder, 1);
  2828.       }
  2829.     else
  2830.       maybe_echo_keys (command_builder, 0);
  2831.       }
  2832.     else if (!NILP (leaf))
  2833.       {
  2834.     if (EQ (Qcommand, echo_area_status (f))
  2835.         && command_builder->echo_buf_index > 0)
  2836.       {
  2837.         /* If we had been echoing keys, echo the last one (without the trailing
  2838.            dash) and redisplay before executing the command. */
  2839.         command_builder->echo_buf[command_builder->echo_buf_index] = 0;
  2840.         maybe_echo_keys (command_builder, 1);
  2841.         Fsit_for (Qzero, Qt);
  2842.       }
  2843.       }
  2844.     RETURN_UNGCPRO (leaf);
  2845.   }
  2846. }
  2847.  
  2848. static Lisp_Object
  2849. execute_command_event_unwind (Lisp_Object datum)
  2850. {
  2851.   if (!NILP (XCAR (datum)))
  2852.     {
  2853.       /* We're doing an abort unwind */
  2854.       reset_this_command_keys (Qt);
  2855.     }
  2856.   free_cons (XCONS (datum));
  2857.   return (Qzero);
  2858. }
  2859.  
  2860. static void
  2861. execute_command_event (struct command_builder *command_builder,
  2862.                        Lisp_Object event)
  2863. {
  2864.   /* This function can GC */
  2865.   /* store last_command_event */
  2866.   {
  2867.     reset_current_events (command_builder);
  2868.  
  2869.     if (XEVENT (event)->event_type == key_press_event)
  2870.       Vcurrent_mouse_event = Qnil;
  2871.     else if (XEVENT (event)->event_type == button_press_event
  2872.           || XEVENT (event)->event_type == button_release_event)
  2873.       Vcurrent_mouse_event = Fcopy_event (event, Qnil);
  2874.  
  2875.     /* Store the last-command-event.  The semantics of this is that it is
  2876.        the last event most recently involved in command-lookup.
  2877.        */
  2878.     if (!EVENTP (Vlast_command_event))
  2879.       Vlast_command_event = Fallocate_event ();
  2880.     if (XEVENT (Vlast_command_event)->event_type == dead_event)
  2881.       {
  2882.     Vlast_command_event = Fallocate_event ();
  2883.     error ("Someone deallocated the last-command-event!");
  2884.       }
  2885.  
  2886.     if (! EQ (event, Vlast_command_event))
  2887.       Fcopy_event (event, Vlast_command_event);
  2888.  
  2889.     /* Note that last-command-char will never have its high-bit set, in
  2890.        an effort to sidestep the ambiguity between M-x and oslash.
  2891.        */
  2892.     Vlast_command_char = Fevent_to_character (Vlast_command_event,
  2893.                                               Qnil, Qnil, Qnil);
  2894.   }
  2895.  
  2896.   /* Actually call the command, with all sorts of hair to preserve or clear
  2897.      the echo-area and region as appropriate and call the pre- and post-
  2898.      command-hooks.
  2899.      */
  2900.   {
  2901.     int old_kbd_macro = kbd_macro_end;
  2902.     int speccount = specpdl_depth ();
  2903.     Lisp_Object locative = Fcons (Qt, Qnil);
  2904.     struct window *w;
  2905.     struct gcpro gcpro1;
  2906.  
  2907.     GCPRO1 (locative); /* just in case ... */
  2908.  
  2909.     w = XWINDOW (Fselected_window (Qnil));
  2910.  
  2911.     /* We're executing a new command, so the old value of is irrelevant. */
  2912.     zmacs_region_stays = 0;
  2913.  
  2914.     /* If the previous command tried to force a specific window-start,
  2915.        reset the flag in case this command moves point far away from
  2916.        that position.  Also, reset the window's buffer's change
  2917.        information so that we don't trigger an incremental update. */
  2918.     if (w->force_start)
  2919.       {
  2920.     w->force_start = 0;
  2921.     buffer_reset_changes (XBUFFER (w->buffer));
  2922.       }
  2923.  
  2924.     /* Now we actually execute the command.
  2925.        If the command completes abnormally (signals an error, or does
  2926.        a throw past us) then we want Vthis_command_keys to get set to Qnil.
  2927.        Otherwise, we want it unchanged.
  2928.        */
  2929.     record_unwind_protect (execute_command_event_unwind, locative);
  2930.  
  2931.     pre_command_hook ();
  2932.  
  2933.     if (XEVENT (event)->event_type == misc_user_event)
  2934.       {
  2935.     call1 (XEVENT (event)->event.eval.function, 
  2936.            XEVENT (event)->event.eval.object);
  2937.       }
  2938.     else
  2939.       {
  2940. #if 0
  2941.     call2 (Qcommand_execute, Vthis_command, Qnil);
  2942. #else
  2943.     Fcommand_execute (Vthis_command, Qnil);
  2944. #endif
  2945.       }
  2946.  
  2947.     /* We completed normally -- don't do reset in unwind-protect */
  2948.     XCAR (locative) = Qnil;
  2949.     unbind_to (speccount, Qnil);
  2950.  
  2951.     post_command_hook ();
  2952.  
  2953.     if (!NILP (Vprefix_arg))
  2954.       {
  2955.     /* Commands that set the prefix arg don't update last-command, don't
  2956.        reset the echoing state, and don't go into keyboard macros unless
  2957.        followed by another command.
  2958.        */
  2959.     maybe_echo_keys (command_builder, 0);
  2960.  
  2961.     /* If we're recording a keyboard macro, and the last command
  2962.        executed set a prefix argument, then decrement the pointer to
  2963.        the "last character really in the macro" to be just before this
  2964.        command.  This is so that the ^U in "^U ^X )" doesn't go onto
  2965.        the end of macro.
  2966.        */
  2967.     if (defining_kbd_macro)
  2968.       kbd_macro_end = old_kbd_macro;
  2969.       }
  2970.     else
  2971.       {
  2972.     /* Start a new command next time */
  2973.     Vlast_command = Vthis_command;
  2974.     reset_this_command_keys (Qnil);
  2975.     /* Emacs 18 doesn't unconditionally clear the echoed keystrokes,
  2976.        so we don't either */
  2977.     reset_key_echo (command_builder, 0);
  2978.       }
  2979.  
  2980.     UNGCPRO;
  2981.   }
  2982. }
  2983.  
  2984. static void
  2985. pre_command_hook (void)
  2986. {
  2987.   last_point_position = BUF_PT (current_buffer);
  2988.   XSETBUFFER (last_point_position_buffer, current_buffer);
  2989.   /* This function can GC */
  2990.   if (!NILP (Vrun_hooks) && !NILP (Vpre_command_hook))
  2991.     call1 (Vrun_hooks, Qpre_command_hook);
  2992.   if (!NILP (Vrun_hooks) && !NILP (Vlocal_pre_command_hook))
  2993.     call1 (Vrun_hooks, Qlocal_pre_command_hook);
  2994. }
  2995.  
  2996. static void
  2997. post_command_hook (void)
  2998. {
  2999.   /* This function can GC */
  3000.   /* Turn off region highlighting unless this command requested that
  3001.      it be left on, or we're in the minibuffer.  We don't turn it off
  3002.      when we're in the minibuffer so that things like M-x write-region
  3003.      still work!
  3004.  
  3005.      This could be done via a function on the post-command-hook, but
  3006.      we don't want the user to accidentally remove it.
  3007.    */
  3008.   if (! zmacs_region_stays
  3009.       /* #### This has the bug that any region set in the minibuffer is
  3010.        * ####  always sticky!  I think the intention was to make selections
  3011.        * ####  in the old buffer stay around whilst the minibuffer was used
  3012.        * ####  but the effect is losing. */
  3013.       && !MINI_WINDOW_P (XWINDOW (Fselected_window (Qnil))))
  3014.     zmacs_deactivate_region ();
  3015.   else
  3016.     zmacs_update_region ();
  3017.  
  3018.   if (!NILP (Vrun_hooks) && !NILP (Vpost_command_hook))
  3019.     call1 (Vrun_hooks, Qpost_command_hook);
  3020.   if (!NILP (Vrun_hooks) && !NILP (Vlocal_post_command_hook))
  3021.     call1 (Vrun_hooks, Qlocal_post_command_hook);
  3022.  
  3023. #if 0 /* FSFmacs */
  3024.   if (!NILP (current_buffer->mark_active))
  3025.     {
  3026.       if (!NILP (Vdeactivate_mark) && !NILP (Vtransient_mark_mode))
  3027.         {
  3028.           current_buffer->mark_active = Qnil;
  3029.           call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
  3030.         }
  3031.       else if (current_buffer != prev_buffer ||
  3032.            BUF_MODIFF (current_buffer) != prev_modiff)
  3033.         call1 (Vrun_hooks, intern ("activate-mark-hook"));
  3034.     }
  3035. #endif /* FSFmacs */
  3036. }
  3037.  
  3038.  
  3039. DEFUN ("dispatch-event", Fdispatch_event, Sdispatch_event, 1, 1, 0,
  3040.   "Given an event object as returned by `next-event', execute it.\n\
  3041. \n\
  3042. Key-press, button-press, and button-release events get accumulated\n\
  3043. until a complete key sequence (see `read-key-sequence') is reached,\n\
  3044. at which point the sequence is looked up in the current keymaps and\n\
  3045. acted upon.\n\
  3046. \n\
  3047. Mouse motion events cause the low-level handling function stored in\n\
  3048. `mouse-motion-handler' to be called. (There are very few circumstances\n\
  3049. under which you should change this handler.  Use `mode-motion-hook'\n\
  3050. instead.)\n\
  3051. \n\
  3052. Menu, timeout, and eval events cause the associated function or handler\n\
  3053. to be called.\n\
  3054. \n\
  3055. Process events cause the subprocess's output to be read and acted upon\n\
  3056. appropriately (see `start-process').\n\
  3057. \n\
  3058. Magic events are handled as necessary.")
  3059.      (event)
  3060.      Lisp_Object event;
  3061. {
  3062.   /* This function can GC */
  3063.   struct command_builder *command_builder = the_command_builder;
  3064.   struct Lisp_Event *ev;
  3065.   Lisp_Object device;
  3066.  
  3067.   CHECK_LIVE_EVENT (event, 0);
  3068.   ev = XEVENT (event);
  3069.  
  3070.   /* Some events don't have devices (e.g. eval events). */
  3071.  
  3072.   device = EVENT_DEVICE (ev);
  3073.   if (NILP (device))
  3074.     device = Fselected_device ();
  3075.   else
  3076.     {
  3077.       /* events on dead devices get silently eaten */
  3078.       if (!DEVICE_LIVE_P (XDEVICE (device)))
  3079.     return Qnil;
  3080.       if (!EQ (device, Fselected_device ()))
  3081.     Fselect_device (device);
  3082.     }
  3083.  
  3084.   switch (XEVENT (event)->event_type) 
  3085.     {
  3086.     case button_press_event:
  3087.     case button_release_event:
  3088.       /* events on dead frames get silently eaten */
  3089.       if (!FRAME_LIVE_P (XFRAME (XEVENT (event)->channel)))
  3090.     break;
  3091.     case key_press_event:
  3092.       {
  3093.     Lisp_Object leaf;
  3094.  
  3095.     leaf = lookup_command_event (command_builder, event, 1);
  3096.     if (KEYMAPP (leaf))
  3097.       /* Incomplete key sequence */
  3098.       break;
  3099.     if (NILP (leaf))
  3100.       {
  3101.         /* At this point, we know that the sequence is not bound to a
  3102.            command.  Normally, we beep and print a message informing the
  3103.            user of this.  But we do not beep or print a message when:
  3104.  
  3105.            o  the last event in this sequence is a mouse-up event; or
  3106.            o  the last event in this sequence is a mouse-down event and
  3107.               there is a binding for the mouse-up version.
  3108.  
  3109.            That is, if the sequence ``C-x button1'' is typed, and is not
  3110.            bound to a command, but the sequence ``C-x button1up'' is bound
  3111.            to a command, we do not complain about the ``C-x button1''
  3112.            sequence.  If neither ``C-x button1'' nor ``C-x button1up'' is
  3113.            bound to a command, then we complain about the ``C-x button1''
  3114.            sequence, but later will *not* complain about the
  3115.            ``C-x button1up'' sequence, which would be redundant.
  3116.  
  3117.            This is pretty hairy, but I think it's the most intuitive
  3118.            behavior.
  3119.          */
  3120.         struct Lisp_Event *terminal
  3121.           = XEVENT (command_builder->most_current_event);
  3122.  
  3123.         if (terminal->event_type == button_press_event)
  3124.           {
  3125.         int no_bitching;
  3126.         /* Temporarily pretend the last event was an "up" instead of a
  3127.            "down", and look up its binding. */
  3128.         terminal->event_type = button_release_event;
  3129.         /* If the "up" version is bound, don't complain. */
  3130.         no_bitching
  3131.           = !NILP (command_builder_find_leaf
  3132.                (command_builder, 0));
  3133.         /* Undo the temporary changes we just made. */
  3134.         terminal->event_type = button_press_event;
  3135.         if (no_bitching)
  3136.           {
  3137.             /* Pretend this press was not seen (treat as a prefix) */
  3138.             if (XEVENT (command_builder->current_events) == terminal)
  3139.                     {
  3140.                       reset_current_events (command_builder);
  3141.                     }
  3142.             else
  3143.                     {
  3144.                       struct Lisp_Event *e;
  3145.                       for (e = XEVENT (command_builder->current_events);
  3146.                            event_next (e) != terminal;
  3147.                            e = event_next (e))
  3148.                         ;
  3149.                       Fdeallocate_event (command_builder->most_current_event);
  3150.                       set_event_next (e, 0);
  3151.                       XSETEVENT (command_builder->most_current_event, e);
  3152.                     }
  3153.             maybe_echo_keys (command_builder, 1);
  3154.             break;
  3155.           }
  3156.           }
  3157.  
  3158.         /* Complain that the typed sequence is not defined, if this is the
  3159.            kind of sequence that warrants a complaint.
  3160.            */
  3161.         reset_key_echo (command_builder, 0);
  3162.         defining_kbd_macro = 0;
  3163.         Vprefix_arg = Qnil;
  3164.         /* Don't complain about undefined button-release events */
  3165.         if (terminal->event_type != button_release_event) 
  3166.           {
  3167.         Lisp_Object keys = current_events_into_vector(command_builder);
  3168.  
  3169.         /* Reset the command builder for reading the next sequence. */
  3170.         reset_current_events (command_builder);
  3171.  
  3172.         /* Run the pre-command-hook before barfing about an undefined
  3173.            key. */
  3174.         Vthis_command = Qnil;
  3175.         pre_command_hook ();
  3176.         /* The post-command-hook doesn't run. */
  3177.         Fsignal (Qundefined_keystroke_sequence, list1 (keys));
  3178.           }
  3179.         /* Reset the command builder for reading the next sequence. */
  3180.         reset_current_events (command_builder);
  3181.         reset_this_command_keys (Qt);
  3182.       }
  3183.     else
  3184.       {
  3185.         Vthis_command = leaf;
  3186.         /* Don't push an undo boundary if the command set the prefix arg,
  3187.            or if we are executing a keyboard macro, or if in the
  3188.            minibuffer.  If the command we are about to execute is
  3189.            self-insert, it's tricky: up to 20 consecutive self-inserts may
  3190.            be done without an undo boundary.  This counter is reset as
  3191.            soon as a command other than self-insert-command is executed.
  3192.          */
  3193.         if (! EQ (leaf, Qself_insert_command))
  3194.           command_builder->self_insert_countdown = 0;
  3195.         if (NILP (Vprefix_arg)
  3196.         && NILP (Vexecuting_macro)
  3197.         && !EQ (minibuf_window, Fselected_window (Qnil))
  3198.         && command_builder->self_insert_countdown == 0)
  3199.           Fundo_boundary ();
  3200.  
  3201.         if (EQ (leaf, Qself_insert_command))
  3202.           {
  3203.         if (--command_builder->self_insert_countdown < 0)
  3204.           command_builder->self_insert_countdown = 20;
  3205.           }
  3206.         execute_command_event (command_builder, event);
  3207.       }
  3208.     break;
  3209.       }
  3210.     case misc_user_event:
  3211.       {
  3212.     /* Jamie said:
  3213.  
  3214.        We could just always use the menu item entry, whatever it is, but
  3215.        this might break some Lisp code that expects `this-command' to
  3216.        always contain a symbol.  So only store it if this is a simple
  3217.        `call-interactively' sort of menu item.
  3218.  
  3219.        But this is bogus.  `this-command' could be a string or vector
  3220.        anyway (for keyboard macros).  There's even one instance
  3221.        (in pending-del.el) of `this-command' getting set to a cons
  3222.        (a lambda expression).  So in the `eval' case I'll just
  3223.        convert it into a lambda expression.
  3224.      */
  3225.     if (EQ (XEVENT (event)->event.eval.function, Qcall_interactively)
  3226.         && SYMBOLP (XEVENT (event)->event.eval.object))
  3227.       Vthis_command = XEVENT (event)->event.eval.object;
  3228.     else if (EQ (XEVENT (event)->event.eval.function, Qeval))
  3229.       Vthis_command =
  3230.         Fcons (Qlambda, Fcons (Qnil, XEVENT (event)->event.eval.object));
  3231.     else if (SYMBOLP (XEVENT (event)->event.eval.function))
  3232.       /* A scrollbar command or the like. */
  3233.       Vthis_command = XEVENT (event)->event.eval.function;
  3234.     else
  3235.       /* Huh? */
  3236.       Vthis_command = Qnil;
  3237.  
  3238.     command_builder->self_insert_countdown = 0;
  3239.     if (NILP (Vprefix_arg)
  3240.         && NILP (Vexecuting_macro)
  3241.         && !EQ (minibuf_window, Fselected_window (Qnil)))
  3242.       Fundo_boundary ();
  3243.     execute_command_event (command_builder, event);
  3244.     break;
  3245.       }
  3246.     default:
  3247.       {
  3248.     execute_internal_event (event);
  3249.     break;
  3250.       }
  3251.     }
  3252.   return (Qnil);
  3253. }
  3254.  
  3255. DEFUN ("read-key-sequence", Fread_key_sequence, Sread_key_sequence, 1, 1, 0,
  3256.   "Read a sequence of keystrokes or mouse clicks.\n\
  3257. Returns a vector of the event objects read.  The vector and the event\n\
  3258. objects it contains are freshly created (and will not be side-effected\n\
  3259. by subsequent calls to this function).\n\
  3260. \n\
  3261. The sequence read is sufficient to specify a non-prefix command starting\n\
  3262. from the current local and global keymaps.  A C-g typed while in this\n\
  3263. function is treated like any other character, and `quit-flag' is not set.\n\
  3264. \n\
  3265. First arg PROMPT is a prompt string.  If nil, do not prompt specially.\n\
  3266. \n\
  3267. If the user selects a menu item while we are prompting for a key-sequence,\n\
  3268. the returned value will be a vector of a single menu-selection event.\n\
  3269. An error will be signalled if you pass this value to `lookup-key' or a\n\
  3270. related function.")
  3271.   (prompt)
  3272.      Lisp_Object prompt;
  3273. {
  3274.   /* This function can GC */
  3275.   struct command_builder *command_builder = the_command_builder;
  3276.   Lisp_Object result;
  3277.   Lisp_Object event = Fallocate_event ();
  3278.   int speccount = specpdl_depth ();
  3279.   struct gcpro gcpro1;
  3280.   GCPRO1 (event);
  3281.  
  3282.   if (!NILP (prompt))
  3283.     CHECK_STRING (prompt, 0);
  3284.   /* else prompt = Fkeymap_prompt (current_buffer->keymap); may GC */
  3285.   QUIT;
  3286.  
  3287.   reset_this_command_keys (Qnil);
  3288.  
  3289.   specbind (Qinhibit_quit, Qt);
  3290.  
  3291.   for (;;)
  3292.   {
  3293.     Fnext_event (event, prompt);
  3294.     if (! command_event_p (XEVENT (event)))
  3295.       execute_internal_event (event);
  3296.     else
  3297.     {
  3298.       if (XEVENT (event)->event_type == misc_user_event)
  3299.         reset_current_events (command_builder);
  3300.       result = lookup_command_event (command_builder, event, 1);
  3301.       if (!KEYMAPP (result))
  3302.       {
  3303.         result = current_events_into_vector (command_builder);
  3304.         reset_key_echo (command_builder, 0);
  3305.         break;
  3306.       }
  3307.       prompt = Qnil;
  3308.     }
  3309.   }
  3310.  
  3311.   Vquit_flag = Qnil;  /* In case we read a ^G; do not call check_quit() here */
  3312.   Fdeallocate_event (event);
  3313.   RETURN_UNGCPRO (unbind_to (speccount, result));
  3314. }
  3315.  
  3316. DEFUN ("this-command-keys", Fthis_command_keys, Sthis_command_keys, 0, 0, 0,
  3317.   "Return a vector of the keyboard or mouse button events that were used\n\
  3318. to invoke this command.  This copies the vector and the events; it is safe\n\
  3319. to keep and modify them.")
  3320.    ()
  3321. {
  3322.   struct Lisp_Event *e;
  3323.   Lisp_Object result;
  3324.   int len;
  3325.  
  3326.   if (NILP (Vthis_command_keys))
  3327.     return (make_vector (0, Qnil));
  3328.   
  3329.   for (e = XEVENT (Vthis_command_keys), len = 0;
  3330.        e;
  3331.        e = event_next (e), len++)
  3332.     ;
  3333.  
  3334.   /* Vthis_command_keys is threaded in reverse-chronological order */
  3335.   result = make_vector (len, Qnil);
  3336.   for (e = XEVENT (Vthis_command_keys);
  3337.        e;
  3338.        e = event_next (e), len--)
  3339.   {
  3340.     Lisp_Object tem = Qnil;
  3341.     XSETEVENT (tem, e);
  3342.     vector_data (XVECTOR (result))[len - 1] = Fcopy_event (tem, Qnil);
  3343.   }
  3344.   return (result);
  3345. }
  3346.  
  3347.  
  3348. int
  3349. poll_fds_for_input (SELECT_TYPE mask)
  3350. {
  3351.   EMACS_TIME sometime;
  3352.   EMACS_SELECT_TIME select_time;
  3353.   SELECT_TYPE temp_mask;
  3354.   int retval;
  3355.  
  3356.   while (1)
  3357.     {
  3358.       EMACS_SET_SECS_USECS (sometime, 0, 0);
  3359.       EMACS_TIME_TO_SELECT_TIME (sometime, select_time);
  3360.       temp_mask = mask;
  3361.       /* To effect a poll, tell select() to block for zero seconds. */
  3362.       retval = select (MAXDESC, &temp_mask, 0, 0, &select_time);
  3363.       if (retval >= 0)
  3364.     return retval;
  3365.       /* else, we got interrupted by a signal, so try again. */
  3366.     }
  3367.  
  3368.   return 0; /* not reached */
  3369. }
  3370.  
  3371. static int signal_event_pipe_initialized;
  3372.  
  3373. void
  3374. signal_fake_event (void)
  3375. {
  3376.   char byte = 0;
  3377.   /* We do the write always.  Formerly I tried to "optimize" this
  3378.      by setting a flag indicating whether we're blocking and only
  3379.      doing the write in that case, but there is a race condition
  3380.      if the signal occurs after we've checked for the signal
  3381.      occurrence (which could occur in many places throughout
  3382.      an iteration of the command loop, e.g. in status_notify()),
  3383.      but before we set the blocking flag.
  3384.  
  3385.      This should be OK as long as write() is reentrant, which
  3386.      I'm fairly sure it is since it's a system call. */
  3387.  
  3388.   if (signal_event_pipe_initialized)
  3389.     /* In case a signal comes through while we're dumping */
  3390.     {
  3391.       int old_errno = errno;
  3392.       write (signal_event_pipe[1], &byte, 1);
  3393.       errno = old_errno;
  3394.     }
  3395. }
  3396.  
  3397. void
  3398. drain_signal_event_pipe (void)
  3399. {
  3400.   char chars[128];
  3401.   /* The input end of the pipe has been set to non-blocking. */
  3402.   while (read (signal_event_pipe[0], chars, sizeof (chars)) > 0)
  3403.     ;
  3404. }
  3405.  
  3406.  
  3407. /************************************************************************/
  3408. /*                            initialization                            */
  3409. /************************************************************************/
  3410.  
  3411. void
  3412. syms_of_event_stream (void)
  3413. {
  3414.   defsymbol (&Qdisabled, "disabled");
  3415.  
  3416.   deferror (&Qundefined_keystroke_sequence, "undefined-keystroke-sequence",
  3417.             "Undefined keystroke sequence", 1);
  3418.   defsymbol (&Qundefined, "undefined");
  3419.   defsymbol (&Qcommand_execute, "command-execute");
  3420.   defsymbol (&Qemacs_handle_focus_change, "emacs-handle-focus-change");
  3421.  
  3422.   defsubr (&Srecent_keys);
  3423.   defsubr (&Sinput_pending_p);
  3424.   defsubr (&Senqueue_eval_event);
  3425.   defsubr (&Semacs_handle_focus_change);
  3426.   defsubr (&Snext_event);
  3427.   defsubr (&Snext_command_event);
  3428.   defsubr (&Sdiscard_input);
  3429.   defsubr (&Ssit_for);
  3430.   defsubr (&Ssleep_for);
  3431.   defsubr (&Saccept_process_output);
  3432.   defsubr (&Sadd_timeout);
  3433.   defsubr (&Sdisable_timeout);
  3434.   defsubr (&Sadd_async_timeout);
  3435.   defsubr (&Sdisable_async_timeout);
  3436.   defsubr (&Sdispatch_event);
  3437.   defsubr (&Sread_key_sequence);
  3438.   defsubr (&Sthis_command_keys);
  3439.  
  3440.   defsymbol (&Qpre_command_hook, "pre-command-hook");
  3441.   defsymbol (&Qpost_command_hook, "post-command-hook");
  3442.   defsymbol (&Qlocal_pre_command_hook, "local-pre-command-hook");
  3443.   defsymbol (&Qunread_command_events, "unread-command-events");
  3444.   defsymbol (&Qunread_command_event, "unread-command-event");
  3445. }
  3446.  
  3447. void
  3448. vars_of_event_stream (void)
  3449. {
  3450. #ifdef HAVE_X_WINDOWS
  3451.   vars_of_event_Xt ();
  3452. #endif
  3453. #if defined (DEBUG_TTY_EVENT_STREAM) || !defined (HAVE_X_WINDOWS)
  3454.   vars_of_event_tty ();
  3455. #endif
  3456. #ifdef HAVE_NEXTSTEP
  3457.   vars_of_event_ns ();
  3458. #endif
  3459.   the_command_builder
  3460.     = (struct command_builder *) xmalloc (sizeof (struct command_builder));
  3461.   the_command_builder->current_events = Qnil;
  3462.   the_command_builder->most_current_event = Qnil;
  3463.   the_command_builder->prefix_events = Qnil;
  3464.   the_command_builder->last_non_function_event = Qnil;
  3465.   the_command_builder->echo_buf_length = 300; /* #### Kludge */
  3466.   the_command_builder->echo_buf =
  3467.     (Bufbyte *) xmalloc (the_command_builder->echo_buf_length);
  3468.   the_command_builder->echo_buf[0] = 0;
  3469.   the_command_builder->echo_buf_index = -1;
  3470.   the_command_builder->echo_esc_index = -1;
  3471.   the_command_builder->self_insert_countdown = 0;
  3472.  
  3473.   staticpro (&the_command_builder->current_events);
  3474.   staticpro (&the_command_builder->prefix_events);
  3475.  
  3476.  
  3477.   recent_keys_ring_index = 0;
  3478.   recent_keys_ring = make_vector (RECENT_KEYS_SIZE, Qnil);
  3479.   staticpro (&recent_keys_ring);
  3480.  
  3481.   Vthis_command_keys = Qnil;
  3482.   staticpro (&Vthis_command_keys);
  3483.  
  3484.   num_input_chars = 0;
  3485.  
  3486.   command_event_queue = Qnil;
  3487.   staticpro (&command_event_queue);
  3488.  
  3489.   Vlast_selected_frame = Qnil;
  3490.   staticpro (&Vlast_selected_frame);
  3491.  
  3492.   pending_timeout_list = Qnil;
  3493.   staticpro (&pending_timeout_list);
  3494.  
  3495.   pending_async_timeout_list = Qnil;
  3496.   staticpro (&pending_async_timeout_list);
  3497.  
  3498.   the_low_level_timeout_blocktype =
  3499.     Blocktype_new (struct low_level_timeout_blocktype);
  3500.  
  3501.   something_happened = 0;
  3502.  
  3503.   last_point_position_buffer = Qnil;
  3504.   staticpro (&last_point_position_buffer);
  3505.  
  3506.   DEFVAR_INT ("echo-keystrokes", &echo_keystrokes,
  3507.  "*Nonzero means echo unfinished commands after this many seconds of pause.");
  3508.   echo_keystrokes = 1;
  3509.  
  3510.   DEFVAR_INT ("auto-save-interval", &auto_save_interval,
  3511.     "*Number of keyboard input characters between auto-saves.\n\
  3512. Zero means disable autosaving due to number of characters typed.\n\
  3513. See also the variable `auto-save-timeout'.");
  3514.   auto_save_interval = 300;
  3515.  
  3516.   DEFVAR_LISP ("pre-command-hook", &Vpre_command_hook,
  3517.      "Function or functions to run before every command.\n\
  3518. This may examine the `this-command' variable to find out what command\n\
  3519. is about to be run, or may change it to cause a different command to run.\n\
  3520. Function on this hook must be careful to avoid signalling errors!");
  3521.   Vpre_command_hook = Qnil;
  3522.  
  3523.   DEFVAR_LISP ("post-command-hook", &Vpost_command_hook,
  3524.      "Function or functions to run after every command.\n\
  3525. This may examine the `this-command' variable to find out what command\n\
  3526. was just executed.");
  3527.   Vpost_command_hook = Qnil;
  3528.  
  3529.   DEFVAR_LISP ("last-command-event", &Vlast_command_event,
  3530.     "Last keyboard or mouse button event that was part of a command.  This\n\
  3531. variable is off limits: you may not set its value or modify the event that\n\
  3532. is its value, as it is destructively modified by `read-key-sequence'.  If\n\
  3533. you want to keep a pointer to this value, you must use `copy-event'.");
  3534.   Vlast_command_event = Qnil;
  3535.  
  3536.   DEFVAR_LISP ("last-command-char", &Vlast_command_char,
  3537.     "If the value of `last-command-event' is a keyboard event, then\n\
  3538. this is the nearest ASCII equivalent to it.  This the the value that\n\
  3539. `self-insert-command' will put in the buffer.  Remember that there is\n\
  3540. NOT a 1:1 mapping between keyboard events and ASCII characters: the set\n\
  3541. of keyboard events is much larger, so writing code that examines this\n\
  3542. variable to determine what key has been typed is bad practice, unless\n\
  3543. you are certain that it will be one of a small set of characters.");
  3544.   Vlast_command_char = Qnil;
  3545.  
  3546.   DEFVAR_LISP ("last-input-event", &Vlast_input_event,
  3547.     "Last keyboard or mouse button event received.  This variable is off\n\
  3548. limits: you may not set its value or modify the event that is its value, as\n\
  3549. it is destructively modified by `next-event'.  If you want to keep a pointer\n\
  3550. to this value, you must use `copy-event'.");
  3551.   Vlast_input_event = Qnil;
  3552.  
  3553.   DEFVAR_LISP ("last-input-char", &Vlast_input_char,
  3554.     "If the value of `last-input-event' is a keyboard event, then\n\
  3555. this is the nearest ASCII equivalent to it.  Remember that there is\n\
  3556. NOT a 1:1 mapping between keyboard events and ASCII characters: the set\n\
  3557. of keyboard events is much larger, so writing code that examines this\n\
  3558. variable to determine what key has been typed is bad practice, unless\n\
  3559. you are certain that it will be one of a small set of characters.");
  3560.   Vlast_input_char = Qnil;
  3561.  
  3562.   DEFVAR_LISP ("last-input-time", &Vlast_input_time,
  3563.     "The time (in seconds since Jan 1, 1970) of the last-command-event,\n\
  3564. represented as a cons of two 16-bit integers.  This is destructively\n\
  3565. modified, so copy it if you want to keep it.");
  3566.   Vlast_input_time = Qnil;
  3567.  
  3568.   DEFVAR_LISP ("unread-command-events", &Vunread_command_events,
  3569.     "List of event objects to be read as next command input events.\n\
  3570. This can be used to simulate the receipt of events from the user.\n\
  3571. Normally this is nil.");
  3572.   Vunread_command_events = Qnil;
  3573.  
  3574.   DEFVAR_LISP ("unread-command-event", &Vunread_command_event,
  3575.     "Obsolete.  Use `unread-command-events' instead.");
  3576.   Vunread_command_event = Qnil;
  3577.  
  3578.   DEFVAR_LISP ("last-command", &Vlast_command,
  3579.   "The last command executed.  Normally a symbol with a function definition,\n\
  3580. but can be whatever was found in the keymap, or whatever the variable\n\
  3581. `this-command' was set to by that command.");
  3582.   Vlast_command = Qnil;
  3583.  
  3584.   DEFVAR_LISP ("this-command", &Vthis_command,
  3585.     "The command now being executed.\n\
  3586. The command can set this variable; whatever is put here\n\
  3587. will be in `last-command' during the following command.");
  3588.   Vthis_command = Qnil;
  3589.  
  3590.   DEFVAR_LISP ("help-char", &Vhelp_char,
  3591.     "Character to recognize as meaning Help.\n\
  3592. When it is read, do `(eval help-form)', and display result if it's a string.\n\
  3593. If the value of `help-form' is nil, this char can be read normally.\n\
  3594. This can be any form recognized as a single key specifier.\n\
  3595. To disable the help-char, set it to a negative number.");
  3596.   Vhelp_char = make_number (8); /* C-h */
  3597.  
  3598.   DEFVAR_LISP ("help-form", &Vhelp_form,
  3599.     "Form to execute when character help-char is read.\n\
  3600. If the form returns a string, that string is displayed.\n\
  3601. If `help-form' is nil, the help char is not recognized.");
  3602.   Vhelp_form = Qnil;
  3603.  
  3604.   DEFVAR_LISP ("prefix-help-command", &Vprefix_help_command,
  3605.     "Command to run when `help-char' character follows a prefix key.\n\
  3606. This command is used only when there is no actual binding\n\
  3607. for that character after that prefix key.");
  3608.   Vprefix_help_command = Qnil;
  3609.  
  3610.   DEFVAR_LISP ("keyboard-translate-table", &Vkeyboard_translate_table,
  3611.     "String used as translate table for keyboard input, or nil.\n\
  3612. Each character is looked up in this string and the contents used instead.\n\
  3613. If string is of length N, character codes N and up are untranslated.\n\
  3614. This is the right thing to use only if you are on a dumb tty, as it cannot\n\
  3615. handle input which cannot be represented as ASCII.  If you are running emacs\n\
  3616. under X, you should do the translations with the `xmodmap' program instead.");
  3617.   Vkeyboard_translate_table = Qnil;
  3618.  
  3619.   DEFVAR_LISP ("retry-undefined-key-binding-unshifted",
  3620.                &Vretry_undefined_key_binding_unshifted,
  3621.     "If a key-sequence which ends with a shifted keystroke is undefined\n\
  3622. and this variable is non-nil then the command lookup is retried again\n\
  3623. with the last key unshifted.  (e.g. C-X C-F would be retried as C-X C-f.)\n\
  3624. If lookup still fails, a normal error is signalled.");
  3625.     Vretry_undefined_key_binding_unshifted = Qt;
  3626.  
  3627.   Vcontrolling_terminal = Qnil;
  3628.   staticpro (&Vcontrolling_terminal);
  3629. }
  3630.  
  3631. void
  3632. complex_vars_of_event_stream (void)
  3633. {
  3634.   DEFVAR_LISP ("local-pre-command-hook", &Vlocal_pre_command_hook,
  3635.      "Buffer-local function or functions to run before every command.\n\
  3636. This variable is local to each buffer (see also `pre-command-hook').\n\
  3637. This may examine the `this-command' variable to find out what command\n\
  3638. is about to be run, or may change it to cause a different command to run.\n\
  3639. Function on this hook must be careful to avoid signalling errors!");
  3640.   Vlocal_pre_command_hook = Qnil;
  3641.   Fmake_variable_buffer_local (Qlocal_pre_command_hook);
  3642.  
  3643.   defsymbol (&Qlocal_post_command_hook, "local-post-command-hook");
  3644.   DEFVAR_LISP ("local-post-command-hook", &Vlocal_post_command_hook,
  3645.      "Buffer-local function or functions to run after every command.\n\
  3646. This variable is local to each buffer (see also `post-command-hook').\n\
  3647. This may examine the `this-command' variable to find out what command\n\
  3648. was just executed.");
  3649.   Vlocal_post_command_hook = Qnil;
  3650.   Fmake_variable_buffer_local (Qlocal_post_command_hook);
  3651. }
  3652.  
  3653. void
  3654. init_event_stream (void)
  3655. {
  3656.   if (initialized)
  3657.     {
  3658.       /* Do this first; the init_event_*_late() functions
  3659.      pay attention to it. */
  3660.       if (pipe (signal_event_pipe) < 0)
  3661.     {
  3662.       perror ("XEmacs: can't open pipe");
  3663.       exit (-1);
  3664.     }
  3665.       signal_event_pipe_initialized = 1;
  3666.  
  3667.       /* Set it non-blocking so we can drain its output. */
  3668.       set_descriptor_non_blocking (signal_event_pipe[0]);
  3669.  
  3670.       /* WARNING: In order for the signal-event pipe to work correctly
  3671.      and not cause lockups, the following need to be followed:
  3672.  
  3673.      1) event_pending_p() must ignore input on the signal-event pipe.
  3674.      2) As soon as next_event() notices input on the signal-event
  3675.         pipe, it must drain it. */
  3676.       FD_ZERO (&input_wait_mask);
  3677.       FD_ZERO (&non_fake_input_wait_mask);
  3678.       FD_ZERO (&process_only_mask);
  3679.       FD_ZERO (&device_only_mask);
  3680.  
  3681.       FD_SET (signal_event_pipe[0], &input_wait_mask);
  3682.  
  3683. #ifdef HAVE_X_WINDOWS
  3684.       if (!strcmp (display_use, "x"))
  3685.     init_event_Xt_late ();
  3686.       else
  3687. #endif
  3688. #ifdef HAVE_NEXTSTEP
  3689.     if (!strcmp (display_use, "ns"))
  3690.       init_event_ns_late ();
  3691.     else
  3692. #endif
  3693.       {
  3694.         /* For TTY's, use the Xt event loop if we can; it allows
  3695.            us to later open an X connection. */
  3696. #if defined (HAVE_X_WINDOWS) && !defined (DEBUG_TTY_EVENT_STREAM)
  3697.         init_event_Xt_late ();
  3698. #else
  3699.         init_event_tty_late ();
  3700. #endif
  3701.       }
  3702.       init_interrupts_late ();
  3703.     }
  3704. }
  3705.  
  3706.  
  3707. /*
  3708. useful testcases for v18/v19 compatibility:
  3709.  
  3710. (defun foo ()
  3711.  (interactive)
  3712.  (setq unread-command-event (character-to-event ?A (allocate-event)))
  3713.  (setq x (list (read-char)
  3714. ;      (read-key-sequence "") ; try it with and without this
  3715.       last-command-char last-input-char
  3716.       (recent-keys) (this-command-keys))))
  3717. (global-set-key "\^Q" 'foo)
  3718.  
  3719. without the read-key-sequence:
  3720.   ^Q        ==>  (65 17 65 [... ^Q] [^Q])
  3721.   ^U^U^Q    ==>  (65 17 65 [... ^U ^U ^Q] [^U ^U ^Q])
  3722.   ^U^U^U^G^Q    ==>  (65 17 65 [... ^U ^U ^U ^G ^Q] [^Q])
  3723.  
  3724. with the read-key-sequence:
  3725.   ^Qb        ==>  (65 [b] 17 98 [... ^Q b] [b])
  3726.   ^U^U^Qb    ==>  (65 [b] 17 98 [... ^U ^U ^Q b] [b])
  3727.   ^U^U^U^G^Qb    ==>  (65 [b] 17 98 [... ^U ^U ^U ^G ^Q b] [b])
  3728.  
  3729. ;the evi-mode command "4dlj.j.j.j.j.j." is also a good testcase (gag)
  3730.  
  3731. ;(setq x (list (read-char) quit-flag))^J^G
  3732. ;(let ((inhibit-quit t)) (setq x (list (read-char) quit-flag)))^J^G
  3733. ;for BOTH, x should get set to (7 t), but no result should be printed.
  3734.  
  3735. ;also do this: make two frames, one viewing "*scratch*", the other "foo".
  3736. ;in *scratch*, type (sit-for 20)^J
  3737. ;wait a couple of seconds, move cursor to foo, type "a"
  3738. ;a should be inserted in foo.  Cursor highlighting should not change in
  3739. ;the meantime.
  3740.  
  3741. ;do it with sleep-for.  move cursor into foo, then back into *scratch*
  3742. ;before typing.
  3743.  
  3744. ;make sure ^G aborts both sit-for and sleep-for.
  3745.  
  3746.  (defun tst ()
  3747.   (list (condition-case c
  3748.         (sleep-for 20)
  3749.       (quit c))
  3750.     (read-char)))
  3751.  
  3752.  (tst)^Ja^G    ==>  ((quit) 97) with no signal
  3753.  (tst)^J^Ga    ==>  ((quit) 97) with no signal
  3754.  (tst)^Jabc^G  ==>  ((quit) 97) with no signal, and "bc" inserted in buffer
  3755.  
  3756. Do this:
  3757.   (setq enable-recursive-minibuffers t
  3758.       minibuffer-max-depth nil)
  3759.  ESC ESC ESC ESC    - there are now two minibuffers active
  3760.  C-g C-g C-g        - there should be active 0, not 1
  3761. Similarly:
  3762.  C-x C-f ~ / ?        - wait for "Making completion list..." to display
  3763.  C-g            - wait for "Quit" to display
  3764.  C-g            - minibuffer should not be active
  3765. however C-g before "Quit" is displayed should leave minibuffer active.
  3766.  
  3767. ;do it all in both v18 and v19 and make sure all results are the same.
  3768. ;all of these cases matter a lot, but some in quite subtle ways.
  3769. */
  3770.  
  3771.